Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validate serializer object without the field need for validation
I have a following viewset, class VoteViewSet(viewsets.ModelViewSet): serializer_class = VoteSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(created_by=self.request.user) def get_queryset(self): return Vote.objects.filter(created_by=self.request.user) serializer class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = ('id', 'request') read_only_fields = ('id',) and model. class Vote(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='votes') request = models.ForeignKey(Request, related_name='votes') class Meta: unique_together = [('request', 'created_by')] I am trying to save user's vote but I get IntegrityError: UNIQUE constraint failed when I post a vote for the same request twice. I can fix the error by adding created_by to VoteSerializer however I don't want to have it in my serialized data. What are my options? -
Adding a conditional to my code causes VueJS code to not render
I have the following code in Vue; /* Does early detection on if the user is logged in or not. If the user is not logged in, this code is passed over. This is done to make rendering and compilation of the code faster by filtering out unneeded elements. */ // Debug. Brackets will be placed around 'user-home component later' if djangoUser === "AnonymousUser" { Vue.component('user-home', { template: `<div class=""> <a href="#" style="margin:0px; padding:0px;"> <img class="avatar-img" src="https://i.vimeocdn.com/portrait/58832_300x300"> </a> </div>`, }); var userHomeDiv = new Vue({ el: "#user-home-div", }) } I want to have the conditional there so that if the user isn't logged in, then those elements won't be processed. However, when I add that conditional, whether or not it evaluates to true, it causes all of the custom elements and Vue code to disappear from my HTML. When I remove it, everything works as normal. What could be causing this to happen? -
adding instances from django admin
This is how my classes look. class School(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) cluster = models.ForeignKey(Cluster, on_delete=models.CASCADE) school_name = models.CharField(max_length=250) facilitator = models.CharField(max_length=250) f_number = models.IntegerField() f_email = models.EmailField() school_logo = models.FileField(default='') school_strength = models.IntegerField() In which state, region, cluster are also classes. I have tried to create a network of schools with classification in 3 levels i.e state, region, cluster. I have assumed that when I add schools from django admin I thought it might filter regions if I select state and filter clusters when I select region so that it would be easy. But It doesn't seem to work. Though after selecting a particular state and region while adding a school in the cluster dropdown all the clusters from all the states and regions are coming. Is there a solution for this or as of now we don't have such option in django? -
Where should Django project files be located in a production server to allow multiple authorized users to manage?
If the project will be pulled from git, where should it go? I also need to give multiple authorized users to access and manage the project. Also, how should virtualenv be handled on this scenario? My default virtualenv location would be ~/.env so other users wouldn't be able to access. -
how to automatically add a foreign key in django model form
models.py class OtherData(models.Model): title = models.CharField(max_length=120) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='other_data') class ProductImage(models.Model): other_data = models.ForeignKey(OtherData, verbose_name='Select title') user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product_image') image = models.FileField(blank=True, null=True, upload_to='images/') featured = models.BooleanField(default=False) What I wanted is add images to otherdata instance automatically. I tried writing the views.py as follows. def image_create(request, id=None): other_data = get_object_or_404(OtherData, id=id) form =ImageForm(request.POST or None) if form.is_valid(): instance=form.save(commit=False) instance.other_data = other_data instance.save() But getting the error "DoesNotExist at /image/add/ OtherData matching query does not exist" -
saving date and time of user response in django model field
i am making this app in django where on a particular html template if the user selects a particular response by clicking on it, the date and time at which the user clicked that particular response is stored in my database. part of models.py class userresp(models.Model): rid=models.Integerfield(unique=True,default=0) uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE) resp=models.ForeignKey(elementsound,to_field='csid',on_delete=models.CASCADE) date=models.DateTimeField() time=models.DateTimeField() so how do i store that? and what will be the extra parameters in the DateTimeField of both? -
django get the id value
I have asked this question plenty of times and no one seems to know the answer...i did get answers that had nothing to do with my question. How can i get the table_id value from the html template and then once i get the table_id use that to get the table name using that id. I have 4 tables.. 1 table contains the other 3 tables names and the date they were created. The Primary table structure contains: id (primary key) Name (the tables names in that DB) Date (the date the tables were created) In my table_base.html i use the fucntion table_base to show me all the tables that in there. When i click on a table i get the id like this http...../tables/(table_id)/details Now i need to use that value that i get in table_id to get the the table name and then get all the content of that table using the class Details from views.py views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: … -
pycharm The red wave line cannot be filled
Pycharm imports custom module to run normally but has red line hint, and cannot use code completion function, what should be set? from datetime import datetime from django.db import models from courses.models import Course from users.models import UserProfile The imported packages have red underlining, and cannot be complemented, but the code is running normally, such as and solving -
ValueError at /feed/post/5/comment/ The view feed.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead
I am using this exact code in another project, the only difference is that I have changed the model names, urls patterns, and template names since it is a different project. However, I am getting this error and I have no idea why. I am trying to bring the user to a detail page that has both the post and any comments on the post, as well as a link that takes to a page that allows the user to add a comment to the post. app Views.py: @login_required def add_comment_to_post(request,pk): post = get_object_or_404(UserPost,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('feed:post_detail', pk=userpost.pk) else: form = CommentForm() return render(request,'feed/comment_form.html',{'form':form}) userpost_detail.html (post_detail in urls) {% extends 'base.html' %} {% block content %} <h1 class="posttitle">{{ userpost.title }}</h1> <p class="postcontent">{{ userpost.post_body }}</p> {% if request.user.is_authenticated and request.user == post.author %} <a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a> {% endif %} <hr> <a href="{% url 'feed:add_comment' userpost.id %}">Add Comment</a> <div class="container"> {% for comment in post.comments.all %} <br> {% if user.is_authenticated or comment.approved_comment %} {{ comment.create_date }} <a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}"> <span class="glyphicon glyphicon-remove"></span> </a> <p>{{ comment.comment_body }}</p> <p>Posted … -
Create a form that uses attributes from 2 different models
I'm trying to create a form that blends elements from a couple different places. I think the best way to do this may be 2 different forms and showing them on the same page, unless someone else can help me pop it all into one form? I see no problem using 2 forms but I'm kind of unsure how to proceed (and maybe I don't need to!). I have 2 classes that are somewhat related: Person(User) and Friend and they share PersonBenefits. models would look like this: class PersonBenefit(models.Model): benefit = models.ForeignKey(Benefit, null=True) user = models.ForeignKey(User) class Friend(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) has_benefit = models.BooleanField(default=False) ben_id_num = models.CharField(max_length=10, blank=True, null=True) person = models.ForeignKey(User) #good, better, best class BenefitType(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Benefit(models.Model): type = models.ForeignKey(BenefitType) name = models.CharField(max_length=25) The forms.py looks something like this: class GoodBenefitForm(forms.Form): benefit = forms.ModelChoiceField( queryset=Benefit.objects.filter(type__name='Good'), widget = forms.Select(attrs={'class':'g-1-3'}) ) # THIS SHOWS A LIST OF ALL THE FRIENDS FOR THIS USER - DISPLAYS THEIR NAMES NICELY WITH CHECKBOXES friend = forms.ModelMultipleChoiceField( queryset = Friend.objects.none(), widget = forms.CheckboxSelectMultiple(), ) # I WANT THIS TO BE A BUNCH OF TEXTBOXES INSTEAD OF CHECKBOXES - ONE FOR EACH FRIEND FOR THE … -
What is the easiest way to allow users of my Django site to search for posts that I've written on the site?
I don't want to write a search algorithm and I suspect that there must be a library or script to do this. Are there any suggestions? Thank you very much. -
saving audio files in django table(model)
I want to store audio files under an attribute 'soundsrc' in the model elementsound. A part of models.py is given below: models.py(code snippet) class elementsound(models.Model): cdid=models.IntegerField() soundsrc=models.FileField() sounddesc=models.CharField(max_length=20) how do i do that? what changes have to be made in settings.py? please explain in detail. -
uwsgi django 500 internal error
I have been operated server in ubuntu 12. I try to deploy aws in ubuntu 14. but show up 500 server error. nginx + uwsgi + django1.8 Rest of all is same setting. The main page is visible but not css. Another page is same but python do not access into urls.py. (Server Error (500)) my setting is below: [uwsgi] project = project base = /home/ubuntu/example chdir = %(base) module = wsgi:application master = true processes = 1 socket = %(base)/%(project).sock chown-socket = ubuntu:www-data chmod-socket = 664 uid = www-data gid = www-data vacuum = true logto = /home/ubuntu/example/uwsgilog.log connect to my main page url : log is below: [pid: 19749|app: 0|req: 9/9] IP () {42 vars in 716 bytes} [Fri Sep 15 23:18:35 2017] GET / => generated 14405 bytes in 39 msecs (HTTP/1.1 200) 4 headers in 141 bytes (1 switches on core 0) connect to my other page log is below: [pid: 19749|app: 0|req: 11/11] IP () {44 vars in 765 bytes} [Fri Sep 15 23:19:56 2017] GET /search => generated 27 bytes in 34 msecs (HTTP/1.1 500) 4 headers in 145 bytes (1 switches on core 0) What is problem ? -
Django - Forloop Undefined
I have been trying to draw a chess board using Django, Python, CSS, and HTML. To do this, I need to keep track of the number of iterations in my for loop. I read through Django's documentation and saw that I should use forloop.counter. When I used forloop.counter in my program, I received a jinja2.exceptions.UndefinedError which stated that forloop was undefined. I uninstalled and reinstalled Django 1.11.5 in my IDE and received the same error. I installed Django's development version and received the same error. I checked my usage of forloop.counter in a separate test program, and I still received an error saying that forloop was undefined. Is there an error with Django itself? Thank you. Here is the test program: <div id="container"> {% block main %} {% for item in length %} <p>{{ forloop.counter }}</p> {% endfor %} {% endblock %} </div> -
Annotate with django-graphene and filters
I would like to sum a field in my resolver of django-graphene using the django_filter. Typically my resolvers would look like: my_model = DjangoFilterConnectionField( MyModelNode, filterset_class=MyModelFilter) def my_resolver(self, args, context, info): return MyModelFilter( data=format_query_args(args), queryset=self).qs Which works fine. However, I would like to provide a custom queryset to the model filter so that I can perform aggregations on fields. I'm trying to do something like this: def my_resolver(self, args, context, info): queryset = MyModel.objects.values( 'customer_id').annotate( cost_amt=Sum('cost_amt', output_field=FloatField())) return MyModelFilter( data=format_query_args(args), queryset=queryset).qs Inspecting the raw SQL in GraphiQL, it looks correct. However, the error message I receive from GraphQL is "message": "Received incompatible instance \"{'cost_amt': 260.36, 'customer_id': 300968697}\"." This is the correct result, but I'm unsure why GraphQL is getting this object from django-graphene. How can I provide a custom queryset and make this work? -
How use Django Cache in view without cache all page
I trying to use Django Cache to make better my views. Works great, 400ms to 8ms is perfect. But when user access page for the first time, Django cache page with user info in header and when I try log out, page continue with user info. I try use cache in template too, but isn't good, my problem come from view, so continue 400ms. -
saving image files in django model
i want to store a lot of images in a table(model of django) under an attribute 'imgsrc'. How do i do that? i have seen a lot of online material but i am not getting the complete information anywhere. What changes do i need to do in settings.py and where do i store my image files?... a part of models.py class elementdetails(models.Model): sid=models.IntegerField() imgsrc=models.ImageField() soundsrc=models.FileField() sounddesc=models.CharField(max_length=20) -
Iterating through json list in Django template
Apologies, if this question is asked earlier also but currently not able to fetch any answers even after Googling this for a while. I am passing the following context in my Django template : context = {'test': custom_json_list} And the output of custom_json_list is this : {'pc_16530587071502': [{'people_count_entry__sum': None}], 'pc_17100675958928': [{'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': 4}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}]} I want to display the data in the following format 'pc_16530587071502' : NONE 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : 4 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None How can I proceed with the syntax so that I can see the data in this format. The only thing I was able to decipher is this : {% for key, value in test.items %} {{ key }} <br /> {{ value }} <br /> {% endfor %} Thanks in advance. -
How can I access sheet in a method?
Unresolved reference 'sheet' error happens. I wrote class User(): def __init__(self, sheet_path): self.file = glob.glob(sheet_path) self.construction_area ={} def read(self): for x in self.file: if "$" not in x: book = xlrd.open_workbook(x) sheet = book.sheet_by_index(0) cells = [('user_id', 0, 9), ('name', 4, 0), ('age', 4, 1),] ・ ・ def save(self): ・ ・ for row_index in range(7, sheet.nrows): row = sheet.row_values(row_index) ・ ・ x = User('./data/*.xlsx') x.read() x.save() In sheet of save method the error happens.I added self in front of sheet, but AttributeError: 'User' object has no attribute 'sheet' error happens.Why can't I access 'sheet' ?Is making instance not enough?How can I fix this? -
Django post_save receiver won't save foreign key
I have three models: User (from django.contrib.auth.models), UserProfile and GameCharacter. I setup the following receivers so when a User is created, a UserProfile and a GameCharacter are automatically created as well. @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: user_profile = UserProfile() user_profile.user = instance user_profile.money = 0 user_profile.save() @receiver(models.signals.post_save, sender=UserProfile) def create_user_profile_character(sender, instance, created, *args, **kwargs): if created: instance.character = GameCharacter() # Doesn't work, `character_id` is NULL in databse instance.character.save() instance.save() As expected, it creates two entries in database, a UserProfile and a GameCharacter, but the foreign key to the GameCharacter is not saved, it's NULL in database. It's as if the line instance.character = GameCharacter() didn't exist. My models: class GameCharacter(models.Model): nickname = models.CharField(max_length=255, null=True, blank=True, default=None) server = models.ForeignKey(GameServer, on_delete=models.PROTECT, null=True, blank=True, default=None) is_bot = models.BooleanField(default=False) position = models.CharField(max_length=255, null=True, blank=True, default=None) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') character = models.ForeignKey(GameCharacter, null=True, blank=True, on_delete=models.SET_NULL) money = models.BigIntegerField() I use MySQL and InnoDB as storage engine. Any idea? -
Getting {% load chartit %} on my browser. Charts are not loading using chartit
I am Displaying graphs using Django Chartit and Cassandra 3.0 is my database. I have tried to render a line chart but it's not showing a graph, instead it's showing {% load chartit %}. Please suggest. I have googled but it's not helpful. I think the code in HTML is correct. But I dont have a clue what is going wrong. There is also a an error when i run sync_cassandra. I am also struggling with this error. Please share if any more info are required. AttributeError: 'module' object has no attribute 'index' Below are supplements: Models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals # -*- coding: utf-8 -*- from django.db import models # Create your models here. from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class PqpModel(DjangoCassandraModel): prd_id = columns.BigInt(primary_key=True) X_01 = columns.Decimal() X_02 = columns.Decimal() X_03 = columns.Decimal() X_04 = columns.Decimal() X_05_1 = columns.Decimal() X_05_10 = columns.Decimal() X_05_11 = columns.Decimal() X_05_12 = columns.Decimal() urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.db import models from cassandra.cqlengine import connection from cassandra.cqlengine.management import sync_table … -
The requested URL /admin was not found on this server
I have a django app and i need to deploy it on Apache. I have configured everything, which is apache and mod_wsgi, but I can't get the app to run. Whenever I go to the url usercentral.com/admin, it gives an error saying "The requested URL /admin was not found on this server". usercentral.com works fine though. It shows my folder containing staticfiles. My configuration files are as follows: httpd.conf is: # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so … -
Issue with import name(conflict app name with python module name) in celery
I have an app in django as social(app name) also using 'social_django' module but 'social_django' django have dependency module python 'social' both having same name as 'social' due to this autodiscover_tasks giving wrong path for django app social installed app for django INSTALLED_APPS = [ 'social_django', 'social' ] Steps to reproduce add social_django in installed app also create django app with same name as social now check path coming in fuction find_related_module at /lib/python3.5/site-packages/celery/loaders/base.py the following line is creating the bug pkg_path = importlib.import_module(package).__path__ Expected behavior expected path : /home/user/workspace/project/social Actual behavior actual path:: /lib/python3.5/site-packages/social -
How to make a condition in subquery based on outer query?
I work on Airbnb like app. I have a Flat model and Price model, prices have different types of priority which allows customers create a flexible price range. I stuck with one complicated query. This query should return Flats by date range and calculate prices for this range. Here the part of my models: class Flat(models.Model): prices = models.ManyToManyField( 'Price' related_name='flats' ) price = models.PositiveIntegerField() ... class Price(models.Model): PRIORITY_CHOICES = ((i, i) for i in range(1, 6)) priority = PositiveIntegerField(choices=PRIORITY_CHOICES) start_date = models.DateField() end_date = models.DateField() price = models.PositiveIntegerField() So far I figure it out how to annotate prices with higher priority by each day. I wrote a custom manager for Flat: class FlatManager(models.Manager): def with_prices(self, start, end): days = get_days(start, end) # utils function return list of days prices = {} for day in days: prices[str(day)] = models.Subquery( Price.objects.filter( flats=models.OuterRef('pk')). filter(start_date__lte=day, end_date__gte=day). order_by('-priority'). values('price')[:1] ) return self.annotate(**price_dict) Here is my problem: Some dates in the Flat can be without price blocks, so Flat have its own price field for cases when customer don't won't to use flexible prices. I don't know where I need to add a condition operator in my query. If I add it in the Price … -
To be an expert at Java EE or a good developer at both Django and Java EE? [on hold]
I have a general question on developer thoughts, I am currently working as a Java EE developer, but I love the Django framework, so in my free time at home I develop projects on Django. What do you think as developers is it good to stick to a framework and learn the most out of it, like say to be a Java EE expert or gain a more spherical view and be a good but not expert developer at many frameworks, like Java EE developer and Django developer the same time?