Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploying django with AWS and uwsgi
i am following the official documentation http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html Right now i am on "Basic test", how come when i visit http://ec2-54-68-65-229.us-west-2.compute.amazonaws.com:8000, it does not show up anything? it only shows up: "This site can’t be reached 54.68.65.229 took too long to respond." -
Django - How to GET value from table where I don't have foreign key in table from which I want to GET object?
Let's assume that I have for instance table Object1 with columns id,id_users where id_users is a foreign key of id from auth_user table and table Object2 with columns id,id_object1,sth, where id_object1 is a foreign key of id from Object1 table.ID of Object1 and Object2 is automatically incremented in mySQL database. I would like to have for instance such URL /users/{id}/object2/?sth=123 and I would like to get object from Object2 table where {id} is id of the user from auth_user table (in this case is equals 2) and sth is equals 123 in Object2 table in appropriate field. Let's assume this is my model: class Object1(models.Model): id_users = models.PositiveIntegerField(blank=True) class Object2(models.Model): id_object1 = models.FloatField() sth = models.FloatField() I had quite similar problem which was solved in this post - Django - How can I create POST with foreign key defined in URL? but in this case I don't have foreign key in table from which I want to GET object. I have no idea what is the best way to solve this problem. Thanks in advance. -
django error for attribute for charfield
this is my models.py file models.py from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.Charfield(max_length=500) genre = models.Charfield(max_length=100) album_logo = models.Charfield(max_length=1000) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.Cascade) file_type = models.CharField(max_length=10) song_title = models.Charfield(max_length=250) i am getting errors for not found attribute of CharField error i am getting -
Django model field reference
I have contact model class Contact(models.Model): company = models.CharField(max_length=200, blank=True) vatkey = models.CharField(max_length=200, blank=True) Can i set reference that : when company name is not empty then vatkey is required ? regards -
get_or_create gives IntegrityError: Duplicate entry for key 'PRIMARY'"
This has been driving me crazy, I have the following code: category, created = Category.objects.get_or_create(name=category_name, user=self.user) that raises django.db.utils.IntegrityError: (1062, "Duplicate entry '566' for key 'PRIMARY'") I read on other similar issues on stackoverflow that I need to add defaults in my get_or_create, but the thing is that all my other params apart from the two that I specify have default values. Also, replacing the code above by: try: test = Category.objects.get(name=category_name, user=self.user) except Category.DoesNotExist: test = Category(name=category_name, user=self.user) test.save() Works. What in hell is happening? For info, I am using mysql -
Accessing a widgets value in django template
I need to do an ajax call in django depending on the values set on two date fields and a select dropdown. In order to do that I have to pass those values into javascript function which will be called when a button is click. I have set the form dates fields as Date type and select as Choice field. How can I pass the current values of these to the javascript function? form.html (template): <div class="form-group"> <label class="control-label">* Start Date:</label><br> {{ form.date1 }} </div> <div class="form-group"> <label class="control-label">* End Date:</label><br> {{ form.date2 }} </div><br><br> <div class="form-group"> Category: {{ form.category }} </div> <button type="button" class="btn btn-xs btn-warning" onclick="javascript:check_availability({{ XXX }}, '{% url "find_available" %}');"> Check Now </button> Javascript: function check_availability(date1, date2, category, url) { $.ajax({ type: 'GET', url: url, data: {date1: date1, date2: date2, category: category}, dataType: 'json', success: available_now, error: function() { alert('Unable to find available items') } }); } fucntion available_now () {...} In form.py (view) category = forms.ChoiceField(choices=(...)) date1 = forms.DateField(widget=forms.DateInput()) date2 = forms.DateField(widget=forms.DateInput()) How could I pass those three values set in the widgets in place of XXX for the above function call? I need to specifically get the selected value of the dropdown. -
How I can find a project Django + VueJS Server Side Rendering (use Rest Framework API)?
I am finding a project Django + VueJS Server Side Rendering (use Rest Framework API)? I use Hackernews Demo (VueJS Server Side Rendering Demo Project) and try to make API Rest Framework but I can't. -
How to set RQ Worker variables
I'm currently working on a project which is deployed in 6 physical stores and a server in the cloud that requires data to be mirrored at all times. To do this, the servers use a mix of Django and Twisted to alert one another whenever new data that needs to be mirrored is created. This means running UNX sockets so that the Django endpoints can call on the Twisted server to send a notification to the other stores. I want to bypass the need to use UNX sockets however and got the idea to use RQ. Problem is, I need the rq worker to have a reference to the twisted tcp socket in order to do this. Any ideas how I can have this work? -
Django custom app template: How to create directory with app name?
The standard Django app template that runs when one invokes startapp creates the following files and directories: <app_name> |-- migrations | | | +-- __init__.py | |-- __init__.py |-- admin.py |-- apps.py |-- models.py |-- test.py |-- views.py I want to create a custom template that will product the following app structure: <app_name> |-- migrations | | | +-- __init__.py | |-- static | | | |-- <app_name> | | | |-- css | |-- img | |-- js | |-- templates | | | |-- <app_name> | | | |-- index.html | |-- __init__.py |-- admin.py |-- apps.py |-- models.py |-- test.py |-- views.py The trick I am missing is how to setup a template so that certain directories are named using the app name. This is easy to do for parameters within template files but I am not sure if there's a way to create the directories under static and template. Going to go look at startapp source code for clues. Hoping someone might have an answer for this just the same. Thanks. -
find out null values of a row django
I have bellow details : Models.py: class ip(models.Model): IP=models.CharField(max_length=20) created_date=models.DateTimeField(auto_now_add=True,null=True) url=models.URLField(null=True) agent=models.CharField(max_length=200,null=True) country=models.CharField(max_length=200,null=True) isp=models.CharField(max_length=200,null=True) def __unicode__(self): return self.IP I have some null values in country field , but no null value to IP, Now i want to find out only those IPs which is having country as null value .From the bellow given lines i can see the unique IPs v=[] for o in ip.objects.values_list('IP'): if o in v: pass else: v.append(o) Now i want to only those ips which is having null value on country field. -
How to save (store) PDF file generated by weasyprint to specified directory?
I need my pdf files that is generated by weasyprint to be some specified folder, for example in the folder "my_project/pdf_files/" NOTE: I am using django framework for my project. And here is the structure of project. my_project/ ----pdf_generator_app/ --------admin.py --------models.py --------views.py pdf_files/ Currently I have this in my views.py def generate(student_id): student = get_object_or_404(Student, application_id=student_id) html = render_to_string('contract.html', {'student': student}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="some_file.pdf"' weasyprint.HTML(string=html).write_pdf('myfile.pdf', presentational_hints=True, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + '/css/styles.css')]) return response But this view does not store pdf file to a directory. It simply show file on browser. I need the file to be stored in the directory my_project/pdf_files/ -
Django query for list of specimens of relations
i need to get from db all specimens of relation from db. Currently i try to get this with Msg.objects.filter(Q(u1=request.user)|Q(u2=request.user)) U1 is a sender, U2 is a recipient. (Fields have forgeinkey, to User model) This is app to sending messages between users. And i want create list of conversarions where current logged user is a U1 or U2, and get list to display without duplicates. Only one link for recipient / sender -
How to get form ID in Django view?
My template HTML has many forms and each form is enclosed in a div tag of different id. I want to auto-focus on the form submitted after re-rendering the template from view. For this I thought of passing the form's id to the view and then when I re-render, I would pass on that variable in the context and use it through jQuery to focus on that div. The problem I am facing is - How do I send the form's id to view? Also are there any other ways to solve the root problem? -
Why is the week_day API not working on a model method in Django?
model class Attn(Timestamp): dt = models.DateField() @property def saturday(self): return self.dt__week_day == 7 I am trying to find the number of entries in the model that was a Saturday. I found the API from here. So I made a list comprehension as following. view len([1 for i in attns if i.saturday]) When I run the view it shows AttributeError. 'Attn' object has no attribute 'dt__week_day' What am I doing wrong here? -
Mezzanine filebrowser for users
I am using mezzanine's TinyMceWidget widget for the website's user forum. Everything works fine except the filebrowser requires the user to have administrator login privilege to upload files. How can I customize it to remove this restriction? -
How to return the same order in dict - django python
I try to build a dict with variables inside. The variables build another dict in the parent dict. for example: json_out = { "articles":{ "entities": articlesList }, "imagesDetails": imagesDetails, "pages": { "grids": { page.grid_id: { "gridLayouts": page.grid.grid_json, "pageGridId": page.grid_id }, }, } } When i return json_out, it is not return with same order all the time. how can I return it with the same order all the time? thanks -
django - how to redirect page after save modelform
I want to redirtect page, after saving modelform. when i pushed save button, page redirecte, but no any things saved. def channelAdd(request): if request.method == 'POST': form = ChannelForm(request.POST) if form.is_valid(): channelid = form.cleaned_data['channelid'] form.save() return HttpResponseRedirect(reverse('updateChannelInfo', args=[channelid])) else: form = ChannelForm() return render(request, 'web/channelAdd.html', {'form':form}) -
Group.send not working in python console?
I tried Group(groupname).send in the python console and it does not seem to work. Why is this? This is my consumers.py arrangement: def ws_connect(message): message.reply_channel.send({"accept": True}) Group(secure_group).add(message.reply_channel) def ws_receive(message): # Nothing to do here Group(secure_group).send({ "text": "Received {}".format(message.content['text']) }) def ws_disconnect(message): Group(secure_group).discard(message.reply_channel) Routing: from channels.routing import route from App.consumers import ( ws_connect, ws_receive, ws_disconnect ) channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] Terminal commands: from channels import Group #import secure_group here Group(secure_group).send({ "text": "Tester" }) All my clients have never recieved the text. -
login selenium tests for django all auth fails
I am using django-allauth==0.32.0 for user authentication and it works when I do it manually (signup/login/logout/etc.). My models.py: class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) signals.py: @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, **kwargs): instance.profile.save() My views.py: @login_required(login_url='/accounts/login/') def CategoryView(request): context = { 'data': 'data', } return render(request, 'myapp/index.html',context) Now, I am trying to write tests with Selenium StaticLiveServerTestCase for it: def test_login(self): uname = "Herbert" pw = "klaus1234" User.objects.create(username=uname,password=pw) login_page = "/accounts/login" self.selenium.get('%s%s' % (self.live_server_url, login_page)) self.selenium.maximize_window() self.selenium.find_element_by_id("id_login").send_keys(uname) self.selenium.find_element_by_id("id_password").send_keys(pw) self.selenium.find_elements_by_tag_name("button")[0].click() When I run it, it looks like I the correct data gets posted into the input fields, exactly how it does when I do it manually. But what I am getting is this: "The username and/or password you specified are not correct." And the page doesn't redirect to the page specified in LOGIN_REDIRECT_URL To validate that the data I am posting is correct I added these lines which don't throw an error: self.assertEqual(1,len(Profile.objects.all())) self.assertEqual(uname,Profile.objects.all()[0].user.username) self.assertEqual(pw,Profile.objects.all()[0].user.password) self.assertEqual(uname,User.objects.all()[0].username) self.assertEqual(pw,User.objects.all()[0].password) What am I missing here? -
Can parent class access variable of other parent class in Python?
When reading the book Django Unleashed, I came across this code snippet. I was wondering why NewsLinkGetObjectMixin can access the class variable startup_slug_url_kwarg, which is define in another base class StartupContextMixin? class NewsLinkGetObjectMixin(): def get_object(self, queryset=None): startup_slug = self.kwargs.get( self.startup_slug_url_kwarg) newslink_slug = self.kwargs.get( self.slug_url_kwarg) return get_object_or_404( NewsLink, slug__iexact=newslink_slug, startup__slug__iexact=startup_slug) class StartupContextMixin(): startup_slug_url_kwarg = 'startup_slug' startup_context_object_name = 'startup' def get_context_data(self, **kwargs): startup_slug = self.kwargs.get( self.startup_slug_url_kwarg) startup = get_object_or_404( Startup, slug__iexact=startup_slug) context = { self.startup_context_object_name: startup, } context.update(kwargs) return super().get_context_data(**context) class NewsLinkCreate(NewsLinkGetObjectMixin, StartupContextMixin, CreateView): -
How to get query parameters from Django Channels?
I need to access the query parameter dict from Django Channels. The url may look like this: ws://127.0.0.1:8000/?hello="world" How do I retrieve 'world' like this: query_params["hello"]? -
Django: Validation Error is not Raising
I would like to raise an error whenever someone inputs the wrong password as their 'old password' when they want to change their password. For some reason however, my template is not catching this ValidationError if it is even being raised (no alert shows up). template: {% if form.errors %} <div class="alert alert-danger" role="alert"><b>{{ error }}</b></div> {% endif %} forms.py: class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = dict(SetPasswordForm.error_messages, **{ 'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."), }) old_password = forms.CharField( label=(""), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True, 'placeholder': 'Current Password'}), ) new_password1 = forms.CharField( label=(""), strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'New Password'}), ) new_password2 = forms.CharField( label=(""), strip=False, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}) ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password -
"python manage.py runserver" no such directory on Mac
no directory I have creat a project before -
Getting certain values to appear in django form
The image attached displays my current problem. Math 270 and Math 280 in the picture were created by another user and not Jay, who created Jays course. However the other user is logged in currently, and not Jay. How can I get only the courses created by the logged in user, not Jay, to appear in that drop down menu? In my views I have the following with attempts to solve the problem: class CreateQuestion(LoginRequiredMixin, CreateView): model = Question fields = ["title", "question", 'classe'] template_name = "attendance_test/add_test.html" def form_valid(self, form): form.instance.instructor = self.request.user return super(CreateQuestion, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateQuestion, self).get_context_data(**kwargs) context['classe'] = Classe.objects.filter(professor=self.request.user.id) return context def get_initial(self): return { 'classe': Classe.objects.filter(professor=self.request.user.id) } My Question model: class Question(models.Model): title = models.CharField(max_length=100) question = models.TextField(max_length=500) date_pub = models.DateTimeField(auto_now_add=True) instructor = models.ForeignKey(Teacher, on_delete=models.CASCADE, default="") # this is where all the courses are showing up, I only want those # created by the "instructor" to show up, not all instructors classe = models.ForeignKey(Classe, on_delete=models.CASCADE, null=True) def professor_classes(self): return Classe.objects.filter(professor=self.professor) Teacher Model: class Teacher(User): isProfessor = models.BooleanField(default=False) professor_courses = models.ForeignKey('Classe', on_delete=models.CASCADE, null=True) This issue would be a problem if there were say as much as 1000 classes, but an instructor only thought … -
Django - How to GET value from table where I don't have foreign key in table from which I want to GET object?
Let's assume that I have for instance table Object1 with columns id,id_users where id_users is a foreign key of id from auth_user table and table Object2 with columns id,id_object1 where id_object1 is a foreign key of id from Object1 table. I would like to have for instance such URL /users/{id}/object2/?sth=123 and I would like to get object from Object2 table where {id} is id of the user from auth_user table (in this case is equals 2) and sth is equals 123 in Object2 table in appropriate field. I had quite similar problem which was solved in this post - Django - How can I create POST with foreign key defined in URL? but in this case I don't have foreign key in table from which I want to GET object. I have no idea what is the best way to solve this problem. Thanks in advance.