These are chat archives for django/django

Aug 2018
Lucas Garcia de Araújo Martins
Aug 10 2018 17:19 UTC
I have a field type file field in model. In Admin when form is invalid the upload the file is lost and show the error in page admin without file uploaded. How do I make?
Aug 10 2018 18:21 UTC
@lukasgarcya Show me and please
And also you traceback
Lucas Garcia de Araújo Martins
Aug 10 2018 18:26 UTC
class Report(models.Model):
    description = models.CharField(max_length=255)

class Activity(models.Model):
    activity = models.CharField(max_length=100, default=u'')
    attachment = models.FileField(upload_to='report/')
    report = models.ForeignKey(Report, on_delete=models.CASCADE)
class ActivityInline(admin.TabularInline):
    model = Activity

class ReportAdmin(admin.ModelAdmin):
    inlines = [ActivityInline]
Aug 10 2018 21:43 UTC
So my problem continues to morph in new and interesting directions and I'm at my wit's end. When testing POST data from a form view, the data does not validate, despite the uploaded file being part of the FILES key in the form data. I've tried going about this in multiple ways and I continue to get error messages. When testing the data in the shell, the form data is able to validate and save, and the email generated from the form content is able to pass through and go through the testing email middleware. So this is clearly a problem with the request.POST data from the form's page.
def send_job_application(request, pk, slug):
    form_class = EmailReviewForm
    title = 'Send Your Job Application!'
    template_name = 'applications\\EmailReview.html'
    user_info = get_object_or_404(Profile,
    job_obj = EmailableAppliedJob.objects.get(pk=pk)

    if request.method == 'POST':
        # data = request.FILES['attachments'].read()
        file_data = request.FILES
        form = form_class(data=request.POST, files=file_data)
        file_loc = 'post_request_log.txt'
        f = open(file_loc, 'w+')
        f.write(str( + '\\n' + str(form.files))
        return redirect('/accounts/account_profile')
        initial = {
            "subject": job_obj.JobTitle,
            "to_email": job_obj.Email,
            decode('unicode_escape').encode('ascii', 'ignore').
        attached_resume = {
            "attachments": user_info.user_resume
        form = EmailReviewForm(data=initial, files=attached_resume)
        qs = {'title': title, 'form': form, 'object': job_obj}
    return render(request, template_name, qs)
class EmailReviewForm(forms.ModelForm):
    logger = logging.getLogger(__name__)

    class Meta:
        model = EmailRecords
        fields = [

        widgets = {'job_listing': forms.HiddenInput()}

    def send_email(self, form):
        if form.is_valid():
            instance = EmailRecords(file_field=form.files)
            subject = form.cleaned_data['subject']
            body = form.cleaned_data['body']
            from_email = form.cleaned_data['from_email']
            to = form.cleaned_data['to_email']
            attachments = form.cleaned_data['attachments']

                with get_connection() as connection:
                    email = EmailMessage(connection=connection)
                    email.subject = subject
                    email.body = body
                    email.from_email = from_email
           = to
            except Exception as e:
                self.logger.exception('and a thing fucked up')
            self.logger.exception('Form is not valid, for some reason!')
            print(Exception, form.errors)
When submitting POST data, the secondary Exception logging functions are activated in the console, which means the POST data is not validating.
<QueryDict: {'csrfmiddlewaretoken': ['YIw0k5fIxRGPZzN0Iar1ZdzhW7HC2uGU7HbkjjvnjwzFNt5NzN8bg2CEOcF6Veut'], 'subject': ['Team Lead, Information Management and Support'], 'from_email': [''], 'to_email': [''], 'body': ['To Whom It May Concern,\r\nI was quite excited to find the listing for [the position] with [your organization].  I am an interdisciplinary-based professional with over nine years experience across social services, administration, research and software development interests.  This is combined with my educational background in Policy Analysis, Healthcare Policy, and Public Management.  The combination of the two make me an excellent candidate for this opportunity.  \r\n\r\nAs you can see from the enclosed resume, I have extensive experience with Quality Assurance and Improvement across organizational processes and pipelines, with a strong focus on engineering elegant and robust solutions.  Prior to obtaining my MPA and entering the consulting world, I had been consistently rewarded for hard work with promotions and increased responsibilities, resulting in opportunities to develop expertise with Case Management, Vendor Management and Purchasing, Process Management and Improvement, and portfolio management. Since that time, I have worked diligently to serve the needs of my clients by providing analysis and insight into their operations and potential for efficiencies in matters related to internal processes and interfacing with external parties.  I have completed projects related to developing financial models to provide dynamic analysis on cost-benefit and cost-efficiency of projects, built databases using MySQL, and built back-end systems for web applications using Python, Django, JavaScript, and the MEAN stack.  Above all, I am a committed technologist who views organizational infrastructure as vital to providing needed analytics and group functionality.  I am dedicated to bringing new and exciting ideas towards helping organizations streamline existing procedures and to improve outcomes across all pipelines.\r\n\r\nI am committed to personal and professional excellence, by developing new areas of expertise, growing my existing skills, and relying on my excellent written and oral communication skills, honed from years of working across clients, vendors, stakeholders, and other professionals within my networks. But most of all, I value working with others and developing meaningful relationships within and across organizations, build teams and communities for success.  My hope is to apply these talents and qualities within [the position] that will help [your organization] prepare for growth and to meet its evolving needs.\r\n\r\nIf you have questions, or if you want to schedule an interview, please contact me via email or phone at (646) 504-8260.  I look forward to meeting you to further discuss employment opportunities with you.\r\n\r\n\r\nThank you,\r\nFrancis J. Secada, MPA']}>\n<MultiValueDict: {'attachments': [<InMemoryUploadedFile: Francis_Secada_-_Resume.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)>]}>
The likely culprit is that the file object as stored in memory is not properly being parsed by the Django server. I have attempted to remedy this in countless ways, but it should just work straight away (upload to the settings-specified Media location).
if anyone has any insight or recommendations, I am all ears. At this point, I just want the form to take in the uploaded .docx file and successfully write it to the FILES attribute of the form instance. I don't even care about fixing the other issue where the existing file is not sufficient to send the form through.
Lucas Garcia de Araújo Martins
Aug 10 2018 21:57 UTC
@fsecada01 @fsecada01 I have the same problem with Django Admin.