Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST, serializing variable/multiple nested OnetoOne relationship
Apologies if the title is unclear as to what the issue is, I'm unsure how to describe it. I have a "parent" survey model which holds my general fields which all surveys have in common. class Survey(models.Model): ... However depending on the type of survey, additional/different fields are required class SurveyA(models.Model): survey = models.OneToOneField( Survey, on_delete=models.CASCADE, primary_key=True ) fieldA = models.TextField() class SurveyB(models.Model): survey = models.OneToOneField( Survey, on_delete=models.CASCADE, primary_key=True ) fieldC = models.TextField() class SurveyN(models.Model): survey = models.OneToOneField( Survey, on_delete=models.CASCADE, primary_key=True ) fieldN = models.TextField() When I serialize a "Survey" object into json, I would like the corresponding SurveryA,B..N object to be serialized along with it, regardless of which type of sub survey is related back in the OnetoOneField. Is this doable? Expected output when serializing all Survey models: [ { "id": 1, "SurveyA": { "fieldA": "this is an 'A' type Survey", } }, { "id": 2, "SurveyB": { "fieldB": "this is an 'B' type Survey", } }, { "id": 3, "SurveyN": { "fieldN": "this is an 'N' type Survey", } } ] -
Django category view
I am new to django and maybe this is a stupid question but i got stuck with this for a while now.. so i have a few categories of meds, like AINS, antidepressants and each of this category has its own meds, and i am trying to show my users all the meds of a specific category: so if a users types in www.namesite.com/meds/AINS the it will show only the meds for that specific category .. AINS.I think that i should get the absolute url of every category and filter all the meds in that specific category? -
Best way to handle one ForeignKey field that can be sourced from multiple Database Tables
I am running into a little bit of unique problem and wanted to see which solution fit best practice or if I was missing anything in my design. I have a model - it has a field on it that represents a metric. That metric is a foreign key to an object which can come from several database tables. Idea one: Multiple ForeignKey fields. I'll have the benefits of the cascade options, direct access to the foreign key model instance from MyModel, (although that's an easy property to add), and the related lookups. Pitfalls include needing to check an arbitrary number of fields on the model for a FK. Another is logic to make sure that only one FK field has a value at a given time (easy to check presave) although .update poses a problem. Then theres added space in the database from all of the columns, although that is less concerning. class MyModel(models.Model): source_one = models.ForeignKey( SourceOne, null=True, blank=True, on_delete=models.SET_NULL, db_index=True ) source_two = models.ForeignKey( SourceTwo, null=True, blank=True, on_delete=models.SET_NULL, db_index=True ) source_three = models.ForeignKey( SourceThree, null=True, blank=True, on_delete=models.SET_NULL, db_index=True ) Idea two: Store a source_id and source on the model. Biggest concern I have with this is needing … -
Error generating a django form with materialize
When I use a template to fill out a form I cannot use the checkboxes, because they come out as if they were disabled and I cannot select them and the password is not saved with a hash if not as simple text I have a form code with a user model with AbstractUser and signals to create multiple roles: class User(AbstractUser): is_administrator = models.BooleanField(default=False) is_satellite = models.BooleanField(default=False) def get_administrator(self): administrator = None if hasattr(self, 'administrator'): administrator = self.administrator return administrator def get_satellite(self): satellite = None if hasattr(self, 'satellite'): satelite = self.satellite return satellite def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Meta: db_table = 'auth_user' class Administrator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) business_name = models.CharField(max_length=30) class Satellite(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) business_name = models.CharField(max_length=30) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def assign_role(sender, instance, **kwargs): if instance.is_administrator: administrator = Administrator(user=instance) administrator.save() elif instance.is_satellite: satellite = Satellite(user=instance) satellite.save() And the form is as follows: from django import forms from .models import ( User, ) class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password', 'is_active', 'is_administrator', 'is_satelite'] labels = { 'username': 'Username', 'first_name': 'Name', 'last_name': 'Surname', 'email': 'Email', 'password': 'Password', 'is_active': 'State', 'is_administrator': 'Administrator', 'is_satellite': 'Satellite', }, widgets = { 'username': … -
Django - Custom file/Image upload getting file path on upload ? process images on upload?
I have a Django app where users would upload Images and certain functions would take the image file path to process them and save the result in the same model. all of this would happen in the file upload view the problem is My functions take the file path which isn't created/committed in the DB yet as I don't save before calling those functions. I tried overriding the save method in the models.py and it didn't work so how can I call the functions after the upload in a convenient way ?? here's the function: # The view for analysing images def upload_view(request,pk=None): patient = get_object_or_404(Patient,pk=pk) if request.method == 'POST': form = forms.ImageForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) image.patient = patient image.enhanced = main(image.original.path) image.segmented = segment(image.enhanced.path) image.enhanced.name = image.enhanced.path.split('media')[1] image.segmented.name = image.enhanced.path.split('media')[1] messages.success(request,"Image added successfully!") image.save() return HttpResponseRedirect(reverse_lazy('patients:patient_detail', kwargs={'pk' : image.patient.pk})) else: form = forms.ImageForm() return render(request, 'patients/upload.html', {'form': form}) else: form = forms.ImageForm() return render(request, 'patients/upload.html', {'form': form}) image.original is the uploaded image the problem is the file path isn't passed correctly and the functions return errors bec of that. (it worked when I made the processing in a different view where it was accessed after the upload) -
ordering self refrence model (workflow steps ordering)
I have a model that's representing a workflow process and another model representing the workflow steps as shown bellow: class Workflow(models.Model): title = models.CharField(max_length=254, null=True, blank=True) def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=254, null=True, blank=True, verbose_name='Step name') workflow = models.ForeignKey(Workflow, on_delete=models.PROTECT, null=True, related_name='steps') next_step = models.ForeignKey('Step', on_delete=models.PROTECT, null=True) def __str__(self): return self.title How can I print the steps in order if the user can change the steps order anytime he wants? I was thinking of adding a priority field but this will forces the system to rearrange the steps every time the user insert a new step in the workflow. -
How to fix "TemplateDoesNotExist at /admin/login/ django/forms/widgets/text.html" error in Django??'
When i put : *python manage.py runserver* it woked but when i want to login in "http://127.0.0.1:8000/admin" it doesn't work . It gives me this message :strong text TemplateDoesNotExist at /admin/login/ django/forms/widgets/text.html , but i already created a superuser and i have django.contrib.admin installed in setting.py plz help me i've been wrking to solve this for about 1 week. -
Circular import on Django everytime I try to run project
So everytime I try to run my django project I get an error about circular import, I've seen a lot of similar things online but none seem to have helped. main urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('job_app.urls')) ] my views.py from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class BaseView(TemplateView): template_name = 'index.html' app urls from django.urls import path from .views import BaseView urlpatters = [ path('', BaseView.as_view(), name='baseview'), ] -
ImportError: cannot import name 'JSONField'
I'm getting the error: File "/home/mark/Nova/nova/lib/fields.py", line 1, in <module> from django.contrib.postgres.fields import JSONField ImportError: cannot import name 'JSONField' when I run python manage.py runserver 0.0.0.0:8888. Even though I already have simplejson installed. pip freeze shows, alabaster==0.7.12 Babel==2.7.0 bcdoc==0.16.0 boto3==0.0.21 botocore==1.0.0b3 certifi==2019.9.11 chardet==3.0.4 defusedxml==0.6.0 Django==1.8.2 django-bulk-update==1.1.4 django-cors-headers==2.0.2 django-facebook==6.0.3 django-pgjsonb==0.0.15 django-redis==4.2.0 django-revproxy==0.9.7 djangorestframework==3.1.3 djangorestframework-httpsignature==1.0.0 docutils==0.15.2 elasticsearch==1.6.0 facebook-sdk==1.0.0 filemagic==1.6 futures==2.2.0 geopy==1.11.0 google-api-python-client==1.5.0 httplib2==0.14.0 httpsig==1.3.0 idna==2.8 Jinja2==2.10.3 jmespath==0.7.1 MarkupSafe==1.1.1 mock==1.0.1 mongoengine==0.10.0 msgpack-python==0.5.6 nose==1.3.7 oauth2client==2.2.0 oauthlib==3.1.0 Pillow==2.8.2 psycopg2==2.8.4 py2neo==2.0.8 pyasn1==0.4.7 pyasn1-modules==0.2.7 pycryptodome==3.9.0 Pygments==2.4.2 PyJWT==1.7.1 pymongo==3.0.3 PySocks==1.7.1 python-dateutil==2.8.0 python-social-auth==0.2.10 python3-memcached==1.51 python3-openid==3.1.0 python3-pika==0.9.14 pytz==2019.3 redis==2.10.3 requests==2.2.1 requests-oauthlib==1.2.0 rsa==4.0 simplejson==3.7.3 six==1.12.0 snowballstemmer==2.0.0 Sphinx==1.3.1 sphinx-rtd-theme==0.1.9 sphinxcontrib-httpdomain==1.3.1 treelib==1.3.0 twilio==5.6.0 Unidecode==1.1.1 uritemplate==0.6 urllib3==1.10.1 What would be the fix for this? -
Compare two dictionaries returned from REST framework using pytest
I am trying to test my django application with pytest. I am trying to send an object like so: { "x" :1 "y" :2 .... } What my view does, is returning a list of dictionaries, so in my scenario a list with this one sent dictionary. I want to check if my sent data equals my data when I do a get call. My problem is that the two dictionaries are always evaluated to false. This is what I am doing: def test_post_data_is_get_data(self): url = api_reverse('urlname') #I get the url data = sent_data #this is my dict I am sending defined as a big dict in my code response_create = client.post(url, data, format='json') # I save the response response_get = client.get(url) # I get the created data back print(type(response_create.data)) #debugging print(type(data)) print(type(response_create.content)) print(type(response_get)) assert response_create == response_get The types I am printing out is: <class 'rest_framework.utils.serializer_helpers.ReturnDict'> <class 'dict'> <class 'bytes'> Doesn't matter how I compare it is never the same. I tried comparing sent data with: 1) response_create.content == response_get.content 2) response_create.data == response_get.data 3) response_create.data == response_get[0] 4) response_create.data == response_get.first() ## error that byte like object has not attribute first Since I am calling a list view … -
Django - How to make a ForeignKey dropdown toggle-able when there are no options are available in it?
I'm fairly new to Django/python. I have a form that has a dependent dropdown. Based on which work area you choose, your options for station will change, but there are some work areas that do not have any stations, in which case I would like the station dropdown to just not show up, but I'm not sure how to approach this, if it's on the html side or the other forms.py class WarehouseForm(AppsModelForm): """ Warehouse tracking form fields """ class Meta: model = EmployeeWorkAreaLog fields = ('adp_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations}) Here the user only really fills out their # and select work area, so I was wondering if there's a way maybe within the div to make it … -
How to get a button to link to another HTML template in Django?
I'm new to Django, I'm trying to get a button on the homepage to link to another (as of right now) static page. I thought this was pretty simple, I've done frontend work before and a simple href to the file would be enough but for some reason its not linking. <h1> This is the homepage yay!</h1> <div class="container"> <button type="button" href="./scoringsheet.html" class="btn btn-1">Judges</button> <button type="button" class="btn btn-2">Students</button> </div> -
Trying to pass Bokeh Wordcloud2 to Django Templete
I am working on passing data visualization using Bokeh library to Django project. I am able to pass standard Bokeh visualization but when I am trying to used an external wordcloud2 library my project crashes. I receive message "A server error occurred. Please contact the administrator." Any ideas would be much appreciated?! Imports used: from bokeh.plotting import figure, output_file, show from bokeh.embed import components # Bokeh WordCloud from bokeh.io import show from bokeh.models import ColumnDataSource from bokeh_wordcloud2 import WordCloud2 views.py Code below is working: x = [1,2,3,4,5] y = [1,2,3,4,5] plot = figure(title='Line Graph', x_axis_label='x_stuff', y_axis_label='y_stuff', plot_width=400, plot_height=400) plot.line(x, y, line_width=2) auto_div - dynamically generates div elemetent script, auto_div = components(plot) Based on example above, I am trying to pass values for wordcloud in very similar way but it is not working: titles = ['lorem ipsum dolor sit amet', 'consectetur adipiscing elit', 'cras iaculis semper odio', 'eu posuere urna vulputate sed'] test1 = ColumnDataSource({'titles':titles}) wordcloud = WordCloud2(source=test1,wordCol="titles",color=['pink','blue','green']) script, auto_div = components(wordcloud) context = { 'script':script, 'auto_div':auto_div, } return render(request, 'two_boxes/home.html', context) Based on my testing it seems like the problem occurs at script, auto_div = components(wordcloud) statement home.html <head> {% block bokeh_dependencies %} <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css" rel=”stylesheet” type=”text/css”> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.css" rel=”stylesheet” … -
How to update a field in the model using ForegnKey lookup?
I need to be able to update a field num_places in the Event model accessing it via event ForeignKey in the Participant model when the last is saved. Here are my models.py: class Event(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=500) text = models.TextField() image = models.ImageField(blank=True) date = models.DateTimeField() price = models.PositiveIntegerField() num_places = models.PositiveIntegerField(default=50) slug = models.SlugField() class Participant(models.Model): name = models.CharField(max_length=200) participant_uuid = models.UUIDField(primary_key=False, verbose_name='UUID') email = models.EmailField() phone_regex = RegexValidator(regex=r'^\+7\d{10}$') phone_number = models.CharField(validators=[phone_regex], max_length=12) num_places = models.PositiveIntegerField(default=1) event = models.ForeignKey(Event, on_delete=models.CASCADE) paid = models.BooleanField(default=False) def __str__(self): return self.name def save(self, *args, **kwargs): try: self.full_clean(exclude=None) self.event.num_places -= self.num_places # the value isn't updated super().save(*args, **kwargs) self.valid = True self.non_field_errors = False except ValidationError as e: self.non_field_errors = e.message_dict[NON_FIELD_ERRORS] self.valid = False class Meta: unique_together = ('name', 'email', 'phone_number', 'event') The code with a comment has a problem: the num_places value in the Event model stays unchanged. How to fix it? -
Overriding __init__() in class-based form causing AttributeError ('str' object has no attribute 'get')
Each User in my Django application has a 1-to-1 relationship with a Profile object. I want to do some fancy crispy-forms display stuff in my ProfileUpdateForm. When I override init() in my ProfileUpdateForm class, the page breaks with an Attribute Error. I originally suspected the issue is because my users modify their profile at /u/update, with no in the url string. So perhaps the form was not receiving an existing Profile instance. In the traceback, I do see the profile I would expect, so maybe this is not the problem. In my class-based view, I've set get_object() to return self.request.user.profile, so that any user that visits u/update will only be able to update their own profile and not others. This works fine, but as soon as I try overriding init() in my class-based form, the update form breaks. Here's what we have: Form class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ('tagline', 'summary_text_public', 'summary_text_contacts') View class ProfileUpdate(LoginRequiredMixin, generic.UpdateView): form_class = ProfileUpdateForm template_name = 'profile/update.html' success_url = reverse_lazy('profile:redirect_to_self') def get_object(self): return self.request.user.profile URL Pattern path('update/', views.ProfileUpdate.as_view(), name='update'), The code above works as expected, users can update their profiles at u/update. When I add minimal init() code (below) to ProfileUpdateForm, it … -
defined a Form class, but django raised exception saying it is not defined
Followed instructions as on the page. to customize user profile while using django-allauth. Django/python saying it can't find the "SignupForm" class definition, which is clearly defined in the file forms.py in the users app as in the code below. Anyone has any idea what's going on? forms.py from django import forms from allauth.account.forms import AddEmailForm, BaseSignupForm from django.core.exceptions import ValidationError from django.conf import settings from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class SignupForm(BaseSignupForm): first_name = forms.CharField(max_length=30, label='Firstname') last_name = forms.CharField(max_length=150, label='Lastname') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() class MyAddEmailForm(AddEmailForm): def clean_email(self): email = super().clean_email() if self.user.emailaddress_set.count() >= settings.USERS_EMAILS_MAX_COUNT: raise ValidationError('Number of related emails can be no more than %d.' % settings.USERS_EMAILS_MAX_COUNT) return email class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = (...) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = (...) Error message is: File "D:\Python\Django\m4ever\users\admin.py", line 4, in <module> from .forms import CustomUserCreationForm, CustomUserChangeForm File "D:\Python\Django\m4ever\users\forms.py", line 3, in <module> from allauth.account.forms import AddEmailForm, BaseSignupForm File "C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\allauth\account\forms.py", line 261, in <module> class BaseSignupForm(_base_signup_form_class()): File "C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\allauth\account\forms.py", line 249, in _base_signup_form_class fc_classname)) django.core.exceptions.ImproperlyConfigured: Module "users.forms" does not define a "SignupForm" class -
Using django-tables2 form to send selection to another form - nothing saves?
I have a django-tables2 form that passes selected model items to a second form. The goal of the second form is to allow a user to edit values that will be applied to all the items. My problem is that the second form fails validation and then the input values don't get saved. How can I link these two forms and allow user input before the form tries to validate? image_list.html: <form method="post" action="{% url 'ExifReader:delete_image_list' %}"> {% render_table table %} {% csrf_token %} <button type="submit" style="margin-right:10px" class="btn btn-primary" name="edit_FAN">Edit Exif</button> <button type="submit" style="margin-right:10px" class="btn btn-danger" onclick="return confirm('Delete?')" name="delete_images">Delete Images</button> </form> Note: The delete_images button works fine. views.py: def delete_image_list(request): if request.method == 'POST': if 'delete_images' in request.POST: pks = request.POST.getlist('selection') # Delete items... elif 'edit_FAN' in request.POST: form = EditFANForm() pks = request.POST.getlist('selection') imgs = [] for pk in pks: ex = exif.objects.get(pk=pk) imgs.append(ex.image_id) if request.method == 'POST': print('POST') for img in imgs: print(image.objects.get(pk=img)) form = EditFANForm(instance=image.objects.get(pk=img)) if form.is_valid(): print('Valid') formS = form.save(commit=False) img.FAN = formS.FAN fromS.save() else: print('ERRORS: ', form.errors) return render(request, 'ExifReader/edit_fan_form.html', {'form': form, 'pks':pks}) When I click the button for "edit_FAN" from the table view, the EditFANForm renders correctly, I can enter values, get redirected back … -
Can we show Window Service with Django?
I very new in Django and i dont know its possible to show a list of windows service from a Server in web in Django I do this and admin the service with Python (STOP, START and RESTART) but i dont have any GUI or simmilar Thanks -
django debt listing and grouping
I use django, I have 2 questions 1 question: The following code includes the total debt and pays that users pay. But he brings the records twice. Can we group this? I grouped by "id" number again. Question 2: how can we show the result as json? He writes the results twice, he writes once. But there are two results {'customer': 54, 'totalDebtResult': Decimal('150.00'), 'totalreceivedAmount': Decimal('30.00')}, {'customer': 54, 'totalDebtResult': Decimal('150.00'), 'totalreceivedAmount': Decimal('30.00')}, {'customer': 55, 'totalDebtResult': Decimal('250.00'), 'totalreceivedAmount': Decimal('80.00')} {'customer': 55, 'totalDebtResult': Decimal('250.00'), 'totalreceivedAmount': Decimal('80.00')} class DebtListAPIView(ListAPIView): serializer_class = DebtCreateSerializer def get_queryset(self): result = Debt.objects.all().values('customer__id').distinct().annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')).order_by('customer__id') print(result) -
Django - How to make a ForeignKey field toggle if no options are available?
I'm fairly new to Django/python. I have a form that has a dependent dropdown. Based on which work area you choose, your options for station will change, but there are some work areas that do not have any stations, in which case I would like the station dropdown to just not show up, but I'm not sure how to approach this, if it's on the html side or the other forms.py class WarehouseForm(AppsModelForm): """ Warehouse tracking form fields """ class Meta: model = EmployeeWorkAreaLog fields = ('adp_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations}) enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate > {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} … -
HTML not connecting with CSS correctly
In my Django project, I attempt connect HTMl to CSS. I have looked online and at other related problems on stack overflow, and still cannot get html and css to link together. I am also a complete newbie to frontend development. Here's my code (The css file is in the same directory as this file): <head> <link rel="stylesheet" href="signup.css" type="text/css"> </head> <div id="signuptext" class="pb-0"><span>Sign Up</span></div> CSS: #signuptext { font-size: 30px; } Error received: Not Found: /accounts/signup/signup.css I don't understand this error as my css file is in the same folder as the HTML file. Does anybody know whats wrong? Thank you. -
Render diagram of Django models including properties
I am successfully rendering diagrams of Django models with ./manage.py graph_models. I would like to include model properties as well. I completely understand that they are not a part of the database. However, I believe it might be helpful to have them in the diagram. So far, the box for each model contains pairs of field name - field type. My idea is that properties could be shown as property name - property. Is there a tool which supports such a feature? -
A simple Query having a times of 90ms (fetching usernames)
I'm trying to do a form for my users. In this form I need to get every usernames because the users will select one of them. forms.py getName= forms.ModelChoiceField(queryset=CustomUser.objects.values_list('username', flat=True) template.html {{ form.getName}} Django debug toolbar screenshot Here is the time with only 1 user. How comes it take so much time ? My page's loading speed goes from 80ms to 400ms with it. Thanks for the help ! -
ImportError: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference
I'm running an installation script that installs a number of different python packages. The one that is getting stuck on is psycopg2. The script attempts to install version 2.6.1. But I run into the error: Error: could not determine PostgreSQL version from '10.10' I figured it has something to do with the version of psycopg2 that's incompatible with postgresql version 10.10. Is this an invalid conclusion? Assuming my conclusion of version incompatibility is correct I changed the installation version of psycopg2 to 2.7. By doing that the error above went away. However, when I run: python manage.py runserver 0.0.0.0:888 I get the error: File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/django/contrib/postgres/apps.py", line 7, in <module> from .signals import register_hstore_handler File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/django/contrib/postgres/signals.py", line 1, in <module> from psycopg2 import ProgrammingError File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: /home/mark/.virtualenvs/nova/lib/python3.6/site-packages/psycopg2/.libs/./libresolv-2-c4c53def.5.so: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference This makes me think that, maybe version 2.6.1 is probably the version that I needed to use because it's complaining about psycopg2? How do I fix the problem such that I can run the Django development server without the above error? -
How to change the message icon if a message is received
I've built a chat app using Django Channels. To check messages I should click on the message icon (just like stackoverflow for example). I want to add the feature enabling to have these small red circles on the message icon indicating the number of messages not read and I don't even know what I should type on Google to look for this. Any suggestions ? Thanks!