Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect users on Django?
Let's say there's some kind of 'room' called room1. I want users to be able to search for room1 and press connect to join this room. Once they are in this room I can then send them different html pages. Let's say for example 4 people joined room1. Is there a way where I can then hand out a deck of cards between them 4 users and then render different things depending on what card that person got? -
Django edit comment
So i want to do a edit existing comment, but it gives me this error ValueError at /episode/Dragon-Ball-Super/edit/11 The view home.views.edit_comment didn't return an HttpResponse object. It returned None instead. edit_comment def edit_comment(request, slug, id): anime = get_object_or_404(Anime, slug=slug) comment = get_object_or_404(Comment, id=id) form = CommentForm(request.POST, instance=comment.user) if request.method == 'POST': if form.is_valid(): form.save() return redirect('anime_title', slug=slug) else: form = CommentForm() context = {'form': form} return render(request, 'home/edit-comment.html', context) urls.py urlpatterns = [ path('', views.index, name='index'), re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'), re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'), re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'), ] link under existing comment {% if comment.user == request.user.userprofile %} <h6 class="small comment-meta"> <a href="{% url 'edit_comment' slug=anime.slug id=comment.id %}">Edit</a> Delete</h6> {% endif %} models.py class Comment(models.Model): anime = models.ForeignKey(Anime, on_delete=models.CASCADE) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) -
Can I cache rendered data permanently on django?
EXAMPLE: def test(request): if request.method == "POST": pass else: cache_data = cache.get_or_set('render', None) if cache_data is None: rendered_data = render(request, 'website/main/test.html') cache.set('render', rendered_data) return rendered_data else: return cache_data QUESTIONS: I wonder whether I can cache rendered_data like above. And will it works well? How can I set permanent cache using low level cache api? I think it is maybe like.. >>> cache.set('my_key', 'hello, world!', None) or >>> cache.set('my_key', 'hello, world!') . How can I set permanent(has no timeout) cache? -
error http status code must be an integer,
I'm trying to serialize my views, and I get this error about http status code must be an integer, I don't see where is the data that must be integer and is passed as string. I will thankful for any help, I'm new in django. my models.py: class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) location = map_fields.AddressField(max_length=200) preferred = models.ManyToManyField(Place, related_name='Preferred') disliked = models.ManyToManyField(Place, related_name='Disliked') maplocation = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] @classmethod def make_preferred(cls, current_email, new_pref_place): user, created = cls.objects.get_or_create( email=current_email ) user.preferred.add(new_pref_place) @classmethod def remove_preferred(cls, current_email, pref_place): user, created = cls.objects.get_or_create( email=current_email ) user.preferred.remove(pref_)lace @classmethod def make_dislike(cls, current_email, dislike_place): user, created = cls.objects.get_or_create( email=current_email ) user.disliked.add(dislike_place) @classmethod def remove_dislike(cls, current_email, dislike_place): user, created = cls.objects.get_or_create( email=current_email ) user.disliked.remove(dislike_place) class Place(models.Model): name = models.CharField(max_length=200) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular place across whole library") email = models.EmailField(max_length=70,blank=False) city = models.CharField('city', blank=False, default='Rabat', max_length=200, null=False) place_pic = models.ImageField(upload_to = 'pic_folder/', default = 'http://placehold.it/150x150', null= True) location = gis_models.PointField("longitude/latitude", geography=True, blank=False, null=True) #objects = gis_models.GeoManager() def __unicode__(self): return self.name, 'location' File views.py: @login_required @api_view(['GET', 'PUT', 'DELETE']) def home(request, format=None): """ View function for home page of site. """ … -
Django HTML datetime picker
I would like to know, what are the alternatives to show a datetime picker. I use bootstrap and Django. I need to pick month:day and then hour:minute. There have to be two buttons: one is the start date, the second is the end date. The end date cannot be earlier than the start date. Something like this: -
How to cache files from FileField to avoid repeat (Django, DRF)
Summary: I want to cache files that are read in from a FileField in order to optimize performance of the DRF api. Background: The system allows users to upload data files (csv-like) and stores a link to those files using a FileField (django/djangorestframework backends). The model object has additional methods that act on the data stored in the FileField file... i.e. get column names, number of rows, specific data queries (col A from ix 0 -> 10) Each of these methods requires the file to be read in prior to returning data. I'm finding that the required loading and reloading of the file object for every query is costing a ton of CPU & response time. Is there a smart way to cache files that have been read in already (with a timeout) and have django prevent reloading files that are already cached? I've seen some info about memcached but that seems to be more geared toward caching specific API calls rather than the underlying DB objects/data. Thank you for your help! -
Not able to read file from a specific path in ConfigParser of Python
I want to read a file abc.txt from a D:/abc path. My ini file code is [section_a] string_val = world bool_val = false int_val = 11 pi_val = 3.14 This is python script I run as python skipfileparse.py try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser # ver. < 3.0 # instantiate configParser = ConfigParser.RawConfigParser() # parse existing file config.read('skipconfig.ini') # read values from a section string_val = config.get('section_a', 'string_val') bool_val = config.getboolean('section_a', 'bool_val') int_val = config.getint('section_a', 'int_val') float_val = config.getfloat('section_a', 'pi_val') # update existing value config.set('section_a', 'string_val', 'world') # add a new section and some values config.add_section('section_b') config.set('section_b', 'meal_val', 'spam') # save to a file with open('skipconfigwe.ini', 'w') as configfile: config.write(configfile) How to perform same operation for file reading and update from a relative path with new data ? -
Django 2.0 runtime creation of model
I wish to create a model from a csv file (which is an export of a database), but the file format (name and number of columns) can change with every upload of said file, so I can’t define the attributes in advance and it looks like I will have to perform some runtime creation of model. Note: the issue here is not the csv file, converting it to a list of dictionaries is not a problem. There were some old answers and resources ( https://dynamic-models.readthedocs.io/en/latest/topics/model.html#topics-model Django: How to migrate dynamic models made at runtime Django dynamic model fields) but they were not complete or satisfactory. I am looking for updated best practice answer/guidelines for Django 2.0. -
How to access Django's development server using Tor Browser?
I already installed and created a Django project. Then I run the command python manage.py runserver, which gives me: Performing system checks... System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 19, 2018 - 16:28:03 Django version 2.0.4, using settings 'personal.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. All is well, and if I access http://127.0.0.1:8000/ on Mozilla Firefox, I get the initial 'Congratulations!' page with the rocket taking off. If I access http://127.0.0.1:8000/ on Tor Browser, however, I get an 'Unable to connect' error. I can access other websites normally. What's the problem here, and how can I access my development server using Tor Browser instead of Mozilla Firefox? -
Django Connection Pooling to Postgresql
After two days of searching, I thought someone here might be able to help me. I am using Python 3.6 and Django 2.0.4 and pulling client data from a Postgresql database. We process the data to create trends for each client. We then check to see if a trend currently exists and either add a new one or update the existing entry. When this app was single threaded it worked as expected, but was slow. Now that I've tried to add simple multithreading, I'm quickly maxing out my database connections. From what I've read, Django should be using the existing connection instead of opening new connections, but that's not what I'm seeing. Below is a simplified version of what I'm doing. What am I doing wrong and what can I do better to stop opening new db connections? I've looked at pgPool and gpBouncer, but shouldn't Django handle this itself? def trend_starter(date_to_trend, grouping): customer_list = Clearance.objects.distinct('customer').values_list('customer', flat=True) thread_list = [] for cust_name in customer_list: trend_object = TrendSetter(customer=cust_name, mode='RT') trend_thread = threading.Thread(name=cust_name, target=trend_object.trend_setter) thread_list.append(trend_thread) for thread in thread_list: thread.start() sleep(1) for thread in thread_list: thread.join() class TrendSetter(object): def __init__(self, customer, mode): self.customer = customer self.mode = mode def trend_setter(self): customer_data = … -
On click function is partially working to send values from Javascript to views in Django
I am trying to get projectid of respective charts by onClick on my HTML page. That page consists of charts generated dynamically based on data in users table with different projectids If user is having 2 projects or less that HTML page renders to 2 charts and on clicking those charts I will get projectid, which helps me to redirect to dashboard of which that chart belongs to. If user has more than 2 Projects on clicking from third chart, I get null value as project id,though project is existing. g = request.GET , i store my project if in g. Can someone please tell me why same workflow is not returning the required value in other 3 cases and how to how rectify them. Like in below image : enter image description here Here is my Django views method definition def allexist(request): g=request.GET response = {} responseList = [] sentimentlist = [] sentiments1 = [] sentiments2 = [] sentiments3 = [] dt = {} fetchedhash = [] senti_vals = [] positive_list = [] negative_list = [] neutral_list = [] positive_vals = [] negative_vals = [] neutral_vals = [] sentiments = {} jsonStr = [] e=[] if(len(g)>0): a=g["projectid"] else: a=1 … -
Django snippet doesn't show up for everyone
I'm working on a Django/Wagtail. Some editors complained that certain sections of the Admin are not visible for them. I can see them because I have a superuser. I know I could get into the Admin and change the permissions of the different users. But what I really want to do is to be able to change the sections access from the code, that is to say: this section should be visible to everyone. Particularly I'm talking about a section under Snippets that is a proxied model: @register_snippet class ArticleTag(index.Indexed,Tag): class Meta: proxy = True ordering = ('slug',) search_fields = [ index.SearchField('name', partial_match=True), index.SearchField('slug', partial_match=True), ] That section is visible only when the user is Administrator. Also I created a model that is NOT proxied and I face the same issue. I have no idea where the permissions are being defined, since I pretty much copied another model and changed names and variables. And the model I copied from IS visible to editors. Where are the permissions being defined or how can I change the visibility in the code? -
Foreign key constraint error when deleting object, after creating a Django intermediate model
I am getting this error message... ERROR: insert or update on table "topics_alias" violates foreign key constraint "topics_alias_topic_id_5ff5cf5b_fk_topics_topic_id" DETAIL: Key (topic_id)=(141253) is not present in table "topics_topic". STATEMENT: COMMIT ...when I try to delete a Topic that has an Alias associated with it. (This only happens when deleting a topic, and I don't get this error deleting a Topic object that doesn't have an Alias. Updating the Topic with any other data still works, and adding new Aliases to the Topic still works.) I previously was using a simple ManyToManyField to associate Topics to an Item, but moved to an intermediate/intermediary model in order to assign unique values of an attribute (relevance) of a Topic to an Item. Here is what they were before: class Item(models.Model): topics = models.ManyToManyField(Topic, related_name="items", blank=True) class Topic(models.Model): item_count = models.IntegerField(default=0) class Alias(models.Model): name = models.CharField(max_length=200) topic = models.ForeignKey(Topic, related_name='aliases') Here is what they are now: class Item(models.Model): topics = models.ManyToManyField(Topic, through='TopicRelevance', related_name="items", blank=True) class Topic(models.Model): item_count = models.IntegerField(default=0) class Alias(models.Model): name = models.CharField(max_length=200) topic = models.ForeignKey(Topic, related_name='aliases') class TopicRelevance(models.Model): item = models.ForeignKey(Item, related_name="items") topic = models.ForeignKey(Topic, related_name="topics") relevance = models.CharField(max_length=20, blank=True, null=True) I am creating the aliases with something like topic.aliases.get_or_create(name="foo"). I know that … -
django - invoice form - validate the sub totals and net total before save
I have an invoice form made up of two models - Invoice & InvoiceItem - with the help of inlineformset_factory. I have the following jquery snippet to compute the individual totals and net total by reading the price,quantity,tax of each item. function calculateSubTotal(obj){ subTotal = 0 parentDiv = obj.closest('.formset') rate=parseFloat($(parentDiv).find('.rate').val()) quantity=parseInt($(parentDiv).find('.quantity').val()) tax=$(parentDiv).find('.tax option:selected').html()//. tax=tax.match(/\d+/); if(tax) tax=parseFloat(tax[0],10) else return if(!isNaN(rate) && !isNaN(quantity) && $.isNumeric(tax)){ subTotal = rate*quantity*(100+tax)/100 $(parentDiv).find('.total').val(subTotal) } } function calculateTotal() { subTotal=0 $('.total').each(function(){ //console.log($(this).id) console.log($(this).val()) val=parseFloat($(this).val()) subTotal+=val }); if(!isNaN(subTotal)) $('#id_total').val(subTotal) } $(document).ready(function() { $('.formset .form-control').on("blur",function(e){ calculateSubTotal(this); calculateTotal(); }); }); Now, I "believe", I need to make all these calculations on the server-side before save, in order to prevent any manual correction/error by the user in the form. (Correct me if I'm wrong) How do I proceed here? Here's my form_valid() of CreateView. def form_valid(self, form): context = self.get_context_data() item_formset = context['item_formset'] with transaction.atomic(): form.instance.invoice_type=self.kwargs['invoice_type'] self.object = form.save(commit=False) #self.object.save() if item_formset.is_valid(): forms = item_formset.save(commit=False) for form in forms: **#calculate sub-total and assign net-total to parentform.instance.total** item_formset.instance = self.object item_formset.save() return super().form_valid(form) -
How to work with ModelMultiChoiceField
I am trying to save the choices(COURSES_CHOICES) selected by the department in the database and populate(check/select) the same using the data saved in the database. model.py class Choices(models.Model): COURSES_CHOICES = ( ('analysis', 'Analysis'), ('numerical', 'Numerical'), ('networking', 'Networking'), ('philosophy', 'Philosophy') ) courses = models.CharField(max_length=100, blank=True, choices=COURSES_CHOICES, unique=True) class Meta: verbose_name = 'choice' verbose_name_plural = 'choices' def __str__(self): return str(self.courses) class Department(models.Model): dept_name = models.CharField(max_length=50, blank=True) LEVEL_CHOICES = ( ('1', '100'), ('2', '200'), ('3', '300'), ('4', '400') ) level = models.CharField(max_length=1, blank=True, choices=LEVEL_CHOICES, default=0) choices = models.ManyToManyField(Choices) def __str__(self): return self.dept_name I use a ModelMultiChoiceField in order for the department to enroll the courses at once into the ManyToManyField bt i keep on getting this error "Select a valid choice. <QuerySet [<Choices: analysis>, <Choices: numerical>, <Choices: networking>, <Choices: philosophy>]> is not one of the available choices." forms.py class CoursesListForm(forms.ModelForm): courses = forms.ModelMultipleChoiceField(label="Courses", queryset=Choices.objects.all(), widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(CoursesListForm, self).__init__(*args, **kwargs) self.fields['courses'].queryset=Choices.objects.all() class Meta: model = Choices fields = ['courses'] class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = ['dept_name', 'level'] view.py def select_course(request): course_list = Choices.objects.all() if request.method == 'POST': form = CoursesListForm(request.POST) dept = DepartmentForm(request.POST) if form.is_valid() and dept.is_valid(): courses = form.save(commit=False) courses.save() dept.save() # messages.success('Successfully Created!') return redirect('course_registration') else: … -
Django inlineformset unique validation error when one is deleted
I have a model that has a unique_together value. In an inlineformset if I have two forms with the same unique values together I get a validation error on the second one as a non_field_errors. The second one is a "new" one in that it doesn't have an id value. If the second one is marked as deleted then it works fine, but if the first one is marked for deletion (the one with the id value and already existing in the database) then I still get the validation error on the second form. I'm expecting it to delete the first form object and then create a new object with the same unique_together values. There's a lot of moving parts with models and forms and I'm not really sure what's going wrong so I'm not sure how to work around this. I've gotten the same result in Django 1.10 and Django 1.11. -
Use self-increasing arguments in numeric for-loop in Django
I am currently working on django. I have a list of values which stored in 'graphobject', and 'metarange' is defined as range(0,59). In that case, how could I use numbers as argument to display the value stored in graphobject? I tried using following codes but it doesn't work {% for i in metarange %} {% if graphobject.i != '' %} {{ graphobject.i }} {% endif %} {% endfor %} Please tell me how could I do this? -
How can render many to many tags in html in Django
I have created a Tag model and it is a foreign key to Blog model.But I can't render the tags in html template. Here is the Tag model class Tag(models.Model): name = models.CharField(max_length=40) class Meta: verbose_name = "tag" verbose_name_plural = verbose_name def __str__(self): return self.name Here is the Blog model class Blog(models.Model): title = models.CharField(max_length=100, verbose_name='titel') tag = models.ManyToManyField(Tag, blank=True, verbose_name='tag') class Meta: verbose_name = "Blog" verbose_name_plural = verbose_name def __str__(self): return self.title In my Views.py class BlogDetailView(View): def get(self, request, news_pk): blog = Blog.objects.get(id=int(news_pk)) title = news.title tags = blog.tag return render(request, 'news_detail.html', { 'title': title, 'tags': tags }) And in the detail html: I tried two way to render the tag ,both fails. 1. {% for tag in tags %} <span>{{ tag.name }}</span> {% endfor %} This way it comes out nothing. 2. <span>{{ tags.values }}</span> it comes out with many things like this <QuerySet [{'id': 4, 'name': 'eatting'}, {'id': 5, 'name': 'drinking'}, {'id': 7, 'name': 'playing'}]> {{ tags.values_list }} it comes out like <QuerySet [(4, 'eating'), (5, 'drinking'), (7, 'playing')]> Any friend can tell me the right way to render the tags of a blog in html?Thanks very much! -
Django - Source code cannot contain null bytes
Iam new to PYthon and Django When i try to run the server i get This error: Source code cannot contain null bytes -
How to follow url using jinja in django?
urlpattern = [ path('', views.foo, name='foo') path('hello/', views.hello, name='hello') ] <a href="{% url 'myapp:hello' %}">Link</a> .....this will follow the second path WHAT FOR FIRST PATH? <a href="{% url 'myapp:' %}">Link</a> ....not working -
Django rest framework router not found
In my application I'm using ModelViewSet, as for urls I used SimpleRouter(): main.urls urlpatterns = [ url(r'^teams/', include('team.urls', namespace='teams')), ] team.urls router = SimpleRouter() router.register('', views.TeamViewSet, base_name='teams') router.register('players', views.PlayersViewSet, base_name='players') urlpatterns = [ url(r'^', include(router.urls)) ] I want my urls to be like this: http://.../teams/ and http://.../teams/players/. My problem is when i leave router.register('', views.TeamViewSet, base_name='teams') empty it will get a not found 404 to players url, but if i add anything to the first url e.g: router.register('anything', views.TeamViewSet, base_name='teams'), it will work. How can i make the urls the way i want and why isn't it working this way? -
How to implement a class based view when using django- finite state machine in django
I am making a leave process where an applicant will apply for leave and the leave will be queued so that the approver will either approve or reject the leave application. I came across django-fsm and drf-fsm-transitions and I thought of implementing this kind of work flow. I am using django 1.11 + python3 + django_rest_framework to build my API. In the django app I have imported from django_fsm import transition, FSMIntegerField to models.py. Leave Class class Leave(models.Model): LEAVE_STATUS_CREATED = 0 LEAVE_STATUS_APPLIED = 1 LEAVE_STATUS_APPROVED = 2 LEAVE_STATUS_REJECTED = 3 LEAVE_STATUS_PENDING = 4 LEAVE_STATUS_COMPLETE = 5 LEAVE_STATUS_CHOICES = ( (LEAVE_STATUS_CREATED, 'created'), (LEAVE_STATUS_APPLIED, 'applied'), (LEAVE_STATUS_APPROVED, 'approved'), (LEAVE_STATUS_REJECTED, 'rejected'), (LEAVE_STATUS_PENDING, 'pending'), (LEAVE_STATUS_COMPLETE, 'complete'), ) leave_id = models.AutoField(primary_key=True) applicant = models.ForeignKey( Employee, related_name='applicant', on_delete=models.CASCADE, null=True) approver = models.ForeignKey( Employee, related_name='approver', on_delete=models.CASCADE, null=True) applied_on = models.DateTimeField(auto_now_add=True) responded_on = models.DateTimeField(auto_now=True, null=True) leave_type = models.ForeignKey(LeaveType, null=True) approved = models.BooleanField(default=False) rejected = models.BooleanField(default=False) start_date = models.DateField() return_date = models.DateField() leave_status = FSMIntegerField( choices=LEAVE_STATUS_CHOICES, default=LEAVE_STATUS_CREATED, protected=True) comment = models.TextField(max_length=200) leave_subject = models.CharField(max_length=40) leave_reason = models.TextField(max_length=200) total_days = models.IntegerField(null=True) Transition I have then implemented the following transitions in the leave class: @transition(field=leave_status, source=LEAVE_STATUS_CREATED, target=LEAVE_STATUS_APPLIED) def apply(self, comment): self.applicant = applicant self.leave_type = leave_type self.start_date = start_date self.return_date = return_date … -
Python: Using Python to retrieve properties from spring-cloud-config
I have configured a Centralized Configuration for a Spring Boot Application following this tutorial and I am using a spring boot application to read the properties from the above central git repo. Now I am setting up a Django project and I want to read the same properties from the central repo. Have anyone tried this or working on it now. Would like to know how this can be achieved ? Or have to go with the conventional ConfigParser.? Help of any sort is welcome. Thanks. -
Django-filter filter by current user id
First of all, I'm beginner in Django-filter. I need to filter QuerySet by ForignKeys' fields. And exactly author and worker. Model.py class Object(models.Model): class Meta: abstract = True author = models.ForeignKey('Users.User', on_delete=models.CASCADE) class Task(Object): priority_choices = ( ('high', 'Высокий'), ('middle', 'Стандартный'), ('low', 'Низкий'), ) status_choices = ( ('open', 'Открыта'), ('done', 'Выполнена'), ('close', 'Закрыта'), ) name = models.CharField(max_length=140) description = models.TextField() end_date = models.DateField() worker = models.ForeignKey('Users.User', on_delete=models.CASCADE, related_name='worker_set') priority = models.CharField(max_length=15, choices=priority_choices) status = models.CharField(max_length=15, choices=status_choices) Could You give me an advice how I can create filter with 2 radio buttons first must show only Tasks where request.user is an author, second must show only Tasks where request.user is an worker. I need to solve this with Django-filter. -
Django: override form validation to get around this error
I'm working on a Django application which is facing a PostgreSQL database. The database is relatively large, and I have a lot of many-to-many relationships. The one that I am currently having an issue with is the n:m relationship between People and Sources. The app is used mainly by non-technical people to add to the database through Django's built-in admin feature. The primary issue that I was having when I started working on the app was severe page slowdown when editing a Person on the admin site. If the person had too many Sources, each drop-down in the TabularInline representation of sources loaded thousands of entries. I found a workaround and overrode the get_formfield_for_foreignkey() method as follows: def formfield_for_foreignkey(self, db_field, request, **kwargs): field = super(SourceMaterialInline, self).formfield_for_foreignkey(db_field, request, **kwargs) # We will overwrite this method to ONLY return relevant materials on this person materials = SourceMaterial.objects.all() materials_p = SourceMaterial.people.through.objects.all() person_ID = get_ID_from_path(request.path) if not_integer(person_ID): return field materials_pid = materials_p.filter(person_id=person_ID) # The next step is to use these relevant materials to obtain the SourceMaterial objects from the SourceMaterial table relevant_ids = [] for mat in materials_pid: relevant_ids += [mat.sourcematerial_id] relevant_materials = materials.filter(id__in=relevant_ids) # now we can set the queryset so that only …