Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'User' has no attribute 'profile'
Hello Im sorry I'm very new to django and its implementations. The way I understood the one to one method is when I create a user, the framework already creates a user profile for me? But when I type user.profile.email in my console it gives me "User has no attribute profile".I hope you can help me. views.py this is how I create my users def create_user(request) -> HttpResponse: if request.method != 'POST': return render(request, 'Bartr/HTML/SignUp.html') dict= json.loads(request.body) if "username" not in dict or "password" not in dict: return HttpResponse(status=400) username = dict["username"] user_exist = {} user_exist["value"] = exists(username) # if user exists return false and terminate if user_exist["value"] == True: return HttpResponse( json.dumps(user_exist), content_type="application/json" ) ## continue if user doesnt exist else: password = dict["password"] response_data = {} form = UserForm(dict) user = form.save(commit = False) user.set_password(password) user.first_name = dict["name"] user.save() if user is not None: if user.is_active: login(request,user) return HttpResponse( json.dumps(response_data), content_type="application/json" ) models.py The way I understood it is that this will already create the profile instance for me? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.TextField(max_length=100, blank=True) contact_number = models.CharField(max_length=20, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, … -
How transfer data from middleware to view
Got a little problem. In my middleware class i have function. def process_view(self, request, callback, callback_args, callback_kwargs): r = 'test' return None How i can return r to View? -
An error while migrating -"no module named 'social_django'."
I have installed python-social-auht==0.3.6. Then I migrated and got an error: from social_django.models import AbstractUserSocialAuth, UserSocialAuth, Non ce, Association, Code, DjangoStorage ImportError: No module named 'social_django' -
Django 1.10 NoReverseMatch at /polls/1/ while following official django tutorial part 4
I am following Django Tutorial from it's official page. I am in part 4 of the tutorial. After writing results.html, detail.html and updating views according to it's documentation i get an error mentioned below while trying to access /polls/1 from browser. I can't find where the error lies as everything seems to be according to the tutorial. NoReverseMatch at /polls/1/ Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/vote/$'] My polls/urls.py file from django.conf.urls import url from . import views app_name = 'polls' url patterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] My detail.html file is <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action ="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"/> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> My results.html is as follows <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> and my polls/views.py file … -
Django views with Celery task: Render details page with two parameters
I am processing a form in my Celery task and I can already render them after HttpResponseRedirect. Here in my views.py: from django_celery_results.models import TaskResult from .forms import SampleForm from .models import Sample from analysis.tasks import process_sample_input def sample_submit(request): if request.method == "POST": form = SampleForm(request.POST or None, request.FILES or None) if form.is_valid(): #form = form.cleaned_data instance = form.save() task = process_sample_input.delay(instance.id) try: task_result = TaskResult(task_id = task.id) task_result.save() return HttpResponseRedirect(reverse("sample:results_detail", kwargs={"id":instance.id, "task_id":task.id})) except Exception as e: raise e #return results_detail(request, instance.id, task.id) #show the results details else: print form.errors return not_processed(request) else: form = SampleForm() context = { "form": form, } return render(request, "analysis/sample_form.html", context) My problem is how can I access the html rendered by results_detail from a results list page. I don't know how I can access my Celery task ID elsewhere from the views' sample_submit() In my views.py: def results_list(request): all_samples = Sample.objects.all() context = {'all_samples': all_samples} return render(request, "analysis/results_list.html", context) In my results_list.html {% block content %} <table> <thead> <tr> <th>Name [Local File or URL]</th> </tr> </thead> {% for sample in all_samples %} <td><a href='/sample/results/{{sample.id}}/'>{{ sample.get_sample_name }}</a></td> {% endfor %} </table> {% endblock %} in the myapp/analysis/urls.py: url(r'^results/(?P<id>[0-9]+)/$', views.results_detail, name="results_detail"), Here in urls.py, I can … -
Django: File upload to s3 using boto
I am trying to upload images (average size 12 MB) to my server (django using PIL)then I'm processing them to scale down images and creating thumbnails. During this process I'm not saving images to server local disk instead, I'm using In Memory file and processing it. I'm uploading images to s3, using boto and I have original image, scaled image and the thumbnail which should be uploaded one by one (all these three are still present in my in Memory). This process is very time consuming and sometimes the server which I am using (Digital Ocean 512 MB RAM) throws out of memory error. Can I know is there any better way of uploading images Any help is much appreciated. Thanks in advance. -
How to make object id validation error silent while fetching data mongoengine
I am trying to query the mongodb database using the mongoengine in django Here's the code: Document: class User(Document): name = StringField(max_length=60, required=True) meta = { 'collection': 'users' } and when I try to query the user with the random string as id, It throws error, but I want None or user object: User.objects(id='3sdfs') Here's the error I'm getting raise ValidationError(message, errors=errors, field_name=field_name) mongoengine.errors.ValidationError: '3sdfs' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string -
How to model this kind of a relationship in django?
I want to have two models: class Receipt(models.Model): # Bunch of products class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() I don't want the product to know about receipt but just the receipt to know about the products. How do I build this relationship? -
.css and .html are not located in the same directory
mystyle.css file : table { border-collapse: collapse; } tr, th, td { border: solid 1px #fff } td { width: 50px; padding: 15px } th { background: #006599; color: #fff } table.inner tr:nth-child(even) { background: #c7d4e5 } table.inner tr:nth-child(odd) { background: #E5E5E5 } h1 { margin-bottom: 0; padding: 0.3em 0; border-bottom: 1px solid #777; } h2 { color: #999; font-size: 1.2em; padding-top: 0.4em; } address { padding: 0.8em; font-size: 0.9em; } page { background: white; display: block; margin: 0 auto; margin-bottom: 0.5cm; } page[size="A4"] { width: 21cm; height: 29.7cm; } page[size="A4"][layout="portrait"] { width: 29.7cm; height: 21cm; } page[size="A3"] { width: 29.7cm; height: 42cm; } page[size="A3"][layout="portrait"] { width: 42cm; height: 29.7cm; } page[size="A5"] { width: 14.8cm; height: 21cm; } page[size="A5"][layout="portrait"] { width: 21cm; height: 14.8cm; } .header, .content { padding-right: 30%; } .center { text-align: center; } .border { border: 1px solid #777; } .border td, .border th { border: 1px solid #777; } table { border-collapse: collapse; } table td, table th { border-collapse: collapse; padding: 4px 8px; } @media print { body, page { margin: 0; } .djDebug { display: none; } } @media screen { html { background: #999; } body { margin: 20px 30%; padding-top: 3em; padding-left: … -
{{ form }} versus {{ form.as_table }} in Django template
Style A <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} <!-- Notice this --> </table> <input type="submit" value="Submit"/> </form> Style B <form action="" method="post"> {% csrf_token %} <table> {{ form }} <!-- Notice this --> </table> <input type="submit" value="Submit"/> </form> What's the difference between style A and style B? After some simple experiments, I found that their HTML output is identical. I've read the document, and it seems to imply that these two styles are interchangeable, but I'm not sure. -
Anaconda3\envs\finalproject\lib\site-packages\IPython\html.py:14: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0
I am trying to run a python script(not ipython) using django command but it is giving me the following error C:\Anaconda3\envs\finalproject\lib\site-packages\IPython\html.py:14: ShimWarning: The IPython.html package has been deprecated since IPython 4.0. You should import from notebook instead. IPython.html.widgets has moved to ipywidgets. "IPython.html.widgets has moved to ipywidgets.", ShimWarning) This is strange since the script is a python script.However it was a ipython file before which I then downloaded and converted into a python script. The python script runs fine in spyder IDE but when I try to execute python manage.py runclient It throws me the above error. -
How to pass jquery varibale value to html input box?
how can pass the jquery var value to html input box var m = $("#id_manufacturer").val(); var markup = "<tr><td><input type='checkbox' name='record'></td><td><input type='text' name='phoneManufacturer' value=m/></td></tr> $("table tbody").append(markup); this my code i want pass var m value to input box which i want to save into db via post method i am working on django i have dynamic add row function to add rows and then save it to db -
How to deny requests from unauthorized domains
In Django, there is a settings field ALLOWED_HOSTS in which you put the allowed hosts that can make requests to your route. Is there a quick alternative in Laravel? -
Does Django run multiple threads or processes?
When Django is in production (e.g. sitting behind nginx or something) Does it spawn itself multiple threads to handle requests or processes? -
converting PDF to JPG without Ghostscript or ImageMagick
I'm running Django on a shared hosting and I want to convert PDF to JPGs, possibly using Django, Django-PDF, Django-easy-PDF or PDF 1.0 for python, which I manage to install on the virtual server, and not requiring other dependencies. -
how treat exception in django view?
I have a model with a attribute with 'Unique=True this attribute refers a model that is responsible for evaluate a candidates, a Evaluator can evaluate just one candidate. So when I try evaluate a candidate with the same evaluator the Django return the ValueError, so I tried treat exception, but it don't work...Exist a special way to treat exception in Django? views.py(is in def evaluation ): from django.shortcuts import render, get_object_or_404 from .models import Candidate, Criterion, Evaluation from django import forms from .forms import CandForm from .forms import EvalForm from django.shortcuts import redirect def canditate_list(request): candidates = Candidate.objects.all() eva = Evaluation.objects.all() eval_cand_list = [] #aqui guarda uma lista com os FK candidates convertidos p/ str context = { 'candidates': candidates, 'eva': eva } return render(request, 'app/candidate_list.html',context) def candidate_detail(request, pk): candidate = get_object_or_404(Candidate, pk=pk) c_name = candidate.name #pega o nome (string) do candidato c1 = Evaluation.objects.all() #guarda tds Evaluation na variavel scores = [] #declara a array que vai receber as notas for c in c1: cand = str(c.candidate) #guarda o nome do candidato do Evaluation atual if cand == c_name: #confere se o Evaluation atual corresponde ao candidate atual(pk) scores += [c.score] _sum = 0 #variavel que guardara a soma … -
django query with annotation and conditional count too slow
I have this query with annotations, count and conditional expressions, that runs very slow, it takes forever. I have two models one that stores instagram publications and another one that stores twitter publications. Each publication has also an FK to another model that represents a hexagonal geographical area withina city. Publications [FK] -> HexCityArea TwitterPublication [FK] -> HexCityArea I'm trying to count the publications for each hexagon, but the publications are pre-filtered by other fields like date, so the code is: instagram_publications_ids = list(instagram_publications.values_list('id', flat=True)) twitter_publications_ids = list(twitter_publications.values_list('id', flat=True)) print "\n[HEXAGONS QUERY]> List of publications ids insta\n %s \n" % instagram_publications.query print instagram_publications.explain() print "\n[HEXAGONS QUERY]> List of publications ids twitter\n %s \n" % twitter_publications.query print twitter_publications.explain() # Get count of publications by hexagon resultant_hexagons = HexagonalCityArea.objects.filter(city=city).annotate( instagram_count=Count(Case( When(publication__id__in=instagram_publications_ids, then=1), output_field=IntegerField(), )) ).annotate( twitter_count=Count(Case( When(twitterpublication__id__in=twitter_publications_ids, then=1), output_field=IntegerField(), )) )#filter(instagram_count__gt=0).filter(twitter_count__gt=0) # Discard empty hexagons # For debug only print "\n[HEXAGONS QUERY]> Count of publications\n %s \n" % resultant_hexagons.query print resultant_hexagons.explain() resultant_hexagons_list = list(resultant_hexagons) # Iterate remaining hexagons city_hexagons = [h for h in resultant_hexagons_list if h.instagram_count > 0 or h.twitter_count > 0] As you can see i get first the list of IDs of selected publications and i use them later … -
multiple signup form when using django allauth
I want to customize my signup form and bring a new feature. The new feature is a signup form with two category. One is signup as a developer which will have one more field called experties and another a general signup which will have username, email, password and confirm password. I have done the general signup process but no idea on best way to handle another signup form. And they will be shown on the same page. Signup form as a general user that i could do is ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm' custom_sign_up_form.py class CustomSignupForm(forms.Form): def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data.get('email') if settings.INVITE_MODE: invitation, _ = Invitation.objects.get_or_create(email=email) if not invitation.request_approved: self.add_error('email', 'Sorry at this time you are not invited. But we have added you to our invite list') return email def signup(self, request, user): user.save() signup.html <form class="ui form login" action="{% url 'account_signup' %}" method="POST"> {% csrf_token %} <div class="field"> {% if form.username.errors %} <div class="ui big left icon input error" data-tooltip="{{form.name.errors.0}}" data-position="right center"> {% else %} <div class="ui big left icon input"> {% endif %} <i aria-hidden="true" class="user icon"></i> <input type="text" name="username" class="form-control-ui" placeholder="Username"> </div> </div> <div class="field"> {% if form.email.errors %} <div class="ui … -
Django - Issue having two different forms within one view and calling functions
I have two different forms which I want to display in one view. When I have something like the following then the form will go through and the information will successfully be updated... form1 = Form1(request.POST, request.FILES, instance=profile) form2 = Form2(request.POST, instance=list) if form1.is_valid(): form1.save() return redirect('/dashboard/') else: return render(request, 'detail-edit.html', {'form1':form1,'form2':form2}) However when I change the if statement to include the second form: if form1.is_valid() and form2.is_valid(): form1.save() and form2.save() return redirect('/dashboard/') then this doesn't update any of the information for the models. Is it possible to call is_valid() / save() with two forms at the same time? Thanks -
Creating class instances in a range loop with get_or_create doesn't seem to work
I have a few parsed elements which are python lists now []. Now I need create instance of class for every i element of every list. But if element with the same title already exists, I just need to update. titles = tree.xpath('//div[@class="hidden-info"]/p/text()') images = tree.xpath('//div[@class="posters-middle"]/a/img/@src') cities = tree.xpath('//div[@class="details"]/strong[@class="city"]/text()') places = tree.xpath('//div[@class="details"]/span[@class="place"]/text()') dates = tree.xpath('//div[@class="details"]/span[@class="date"]/text()') for i in m: print(i) event, created = Event.objects.get_or_create(title=titles[i]) event.title = titles[i] # event.image = images[i] event.city = cities[i] # event.place = placies[i] event.date = dates[i] event.save() print (Event.objects.all()) This code is called in some period of time as cron, so I call it with python manage.py runcrons (maybe it somehow has influence over error not showing ) So, iteration doesn't happen, but I haven't found anything wrong and there are no errors in log. The only output now is 0 but if I delete all code in loop expect first line, the iteration works. So why is it wrong? -
Show error when going to /anything if not logged in
SO I have a login reg page that works just fine. I have it show it shows errors if the wrong info or not enough info is put in. However I would like to know what kind of code I can put in to have it auto give a message that you must be logged in to go to another page. Ie prevent people from typing mysite.com/anything here. model.py all this codes works just need to know what to add. Even a link to an idea that I could not find. from future import unicode_literals from django.db import models import re, bcrypt EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]+$') class UserManager(models.Manager): def add_user(self, postData): errors = [] if not len(postData['first_name']): errors.append('First name is required') if len(postData['last_name']) < 2: errors.append('Last name must be at least 2 characters long!') if not len(postData['email']): errors.append('Email is required!') if not EMAIL_REGEX.match(postData['email']): errors.append('Please enter a valid email!') check_email = self.filter(email = postData['email']) if check_email: errors.append('Sorry email already exist!') if len(postData['password']) < 8: errors.append('Password must be at least 8 characters!') if not postData['password'] == postData['confirm_password']: errors.append('Passwords must match!') modelsResponse = {} if errors: # failed validations modelsResponse ['isRegistered'] = False modelsResponse['errors'] = errors else: # passed validations, create a new user … -
Django 1.10 : Query does not exist, but there are 2 model objects in my database
I am trying to render one model at a time. The code looks fine, but I get a redirect because it says it doesn't exist even though there are 2 entities in the database. I have been struggling for a couple hours so any help is appreciated. class Question(models.Model): quizID = models.AutoField(primary_key = True) question = models.CharField(max_length=150, default = '') answerA = models.CharField(max_length=150, default='') answerB = models.CharField(max_length=150, default='') answerC = models.CharField(max_length=150, default='') answerD = models.CharField(max_length=150, default='') correctAnswer = models.CharField(max_length=150, default='') def __str__(self): return self.question class Meta: db_table = "multipleChoice" def view_takeQuiz(request,question): try: quiz = Question.objects.get(question = question) context = {'question': quiz.question, 'answerA': quiz.answerA, 'answerB': quiz.answerB, 'answerC': quiz.answerC,'answerD': quiz.answerD, 'correctAnswer': quiz.correctAnswer} return redirect("https://www.google.com/") except Question.DoesNotExist: # question = None return redirect("https://www.facebook.com/") -
Django how to validate inlineformset so that a field of each form would add up to 100 percent
I am building a form with subcategory using inlineformset. I use inlineform because I want the subcategory to nest under the category. I want to validate a field (weight) of each subcategory form to add up to 100%. I use the clean() but can't get it to work and the error message doesn't show up on the template. I have done some digging form the past posts but don't see any solutions. I also looked into djangoproject but got nowhere. Please help! What am I missing here?!! In my forms.py I have: from django import forms from django.forms.models import inlineformset_factory from .models import Category, SubCategory from django.forms import BaseInlineFormSet class SubInline(BaseInlineFormSet): def clean(self): allocation = 0 for form in self.forms: if not hasattr(form, 'cleaned_data'): continue weight = form.cleaned_data allocation += int(weight.get('weight')) if allocation != 100: raise forms.ValidationError("Weights must sum to 100") SubModelFormSet = inlineformset_factory(Model, SubModel, fields = ['title', 'description', 'weight'], formset = SubInline, extra = 0, can_delete =True) In my views I have: class CategorySubCategoryUpdateView(TemplateResponseMixin, View): template_name = 'manage/subcategory/formset.html' category = None def get_formset(self, data = None): return SubCategoryFormSet(instance = self.category, data=data) def dispatch(self, request, pk): self.category = get_object_or_404(Category, id=pk, owner=request.user) return super(CategorySubCategoryUpdateView, self).dispatch(request) def get(self, request, *args, **kwargs): formset … -
Is it possible to display a PIL Image when running a django site locally through manage.py?
I'm trying to save a jSignature image to a django FileField. My form save code, as it stands, is as follows: def save(self, commit=True): instance = super(ApplicationForRetailInstallmentContractForm, self).save(commit=False) signature = self.cleaned_data.get('signature') signature_image = draw_signature(signature) # at this point, signature_image is a PIL.Image.Image instance signature_image.show() signature_io = StringIO.StringIO() signature_image.save(signature_io, format='JPEG') thumb_file = InMemoryUploadedFile( signature_io, None, '%s signature.jpg' % instance.name, 'image/jpeg', signature_io.len, None, ) instance.signature = thumb_file if commit: instance.save() return instance Currently, when the signature is saved to the filefield, it creates an image with the correct resolution, but that is completely black, which obviously is incorrect. Because we use google buckets for the live version of the site's media, a solution that involves creating actual local files won't work. Ultimately, I have two questions: What could be causing the image to save incorrectly? Is it possible to use something like signature_image.show() (which currently shows no errors but also displays nothing) from within django to view the image as it exists in PIL.Image.Image form, so that I can figure out where in the process the image is getting corrupted? -
Changing image of a node based on JSON data it contains with vis.js without DataSet being defined
I'm working with Vis.js in a django project. I have a network created and I need to be able to to have nodes images change based on the JSON data they hold. I'm having issues doing this because of the whole DataSet needing to be defined in order to use nodes.update etc. I'm unable to predefine the nodes as it's based on the return of another object so the number of nodes are random. Here's my code: This is an example of what the nodes JSON array looks like: [{"id": 1540, "data": [], "label": "AccountFound"}, {"id": 1541, "data": [], "label": "AccountNotFound"}, {"id": 1542, "data": [], "label": "AddANI"}, {"id": 1543, "data": [], "label": "AutoPay"}, {"id": 1544, "data": [], "label": "AutoPayAccount"}, {"id": 1545, "data": [{"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'GetCallerDetail' to 'GreetingDefault'"}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'DNISGreeting' to 'HOOCheck'"}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not found", "title": "Route from 'GreetingDefault' to 'HOOCheck'"}, {"tc_steps": [{"content": "APN: 8552929487, HollyBrowser: , ", "expected": ""}], "title": "Route from 'Start' to 'GetCallerDetail'", "pre_conditions": []}, {"tcs_cannot_route": "This edge cannot be routed: MenuPrompt/MenuPromptWC property 'Outputs' not …