Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using cypress with django in Gitlab CI
I am developing an application using Django and I use Cypress for front-end testing. The setup works locally, but I would like to set-up the testing on gitlab-ci. I have managed to make Gitlab run Cypress tests (while the application runs on production server). What I'd like to achieve (and I am struggling to) is to have Gitlab CI running Django application (probably even with nginx/gunicorn, mimicking the production environment; but embedded dev. server would suffice, too). Is it even possible? To run the server and have Cypress running in the one go? I've seen some examples using docker-compose on Gitlab-CI for nodejs applications - but I'd like to avoid it as setting it all together correctly (so that it uses cache etc.) seems to be super troublesome task. -
Celery class based task is ran synchronously instead of asynchronously
I have used cookiecutter to setup a django project. The relevant parts of the project should be: File config/settings/base.py (should be same as cookiecutter): INSTALLED_APPS += ['foo.taskapp.celery.CeleryAppConfig'] if USE_TZ: CELERY_TIMEZONE = TIME_ZONE CELERY_BROKER_URL = env('CELERY_BROKER_URL', default='redis://redis:6379/0') CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYD_TASK_TIME_LIMIT = 5 * 60 CELERYD_TASK_SOFT_TIME_LIMIT = 60 File foo/taskapp/celery.py (should be same as cookiecutter): import os from celery import Celery from django.apps import apps, AppConfig from django.conf import settings if not settings.configured: # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover app = Celery('foo') class CeleryAppConfig(AppConfig): name = 'foo.taskapp' verbose_name = 'Celery Config' def ready(self): # Using a string here means the worker will not have to # pickle the object when using Windows. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscover_tasks(lambda: installed_apps, force=True) if hasattr(settings, 'RAVEN_CONFIG'): # Celery signal registration # Since raven is required in production only, # imports might (most surely will) be wiped out # during PyCharm code clean up started # in other environments. # @formatter:off from raven import Client as RavenClient … -
Python3 Django Webapp HTML Test Button to print debug data
I am writing a Django web app with python 3 and I would like to add an html button that when clicked prints debug data while I'm testing. I can start successfully run my web app, but I can't seem to figure out how to get my test class to run when I click my html button. My index.html: <!-- this form portion is the important part, everything else works --> <form action='actionUrl' method='GET'> <button id="runScript_btn" type="button" style="height:100px;width:100px" action={{test}}>{{test.x}}</button> </form> My Models.py: class test: x = 1 def printer(self): self.x+=1 print(self.x) return self.x -
Crop an image from x and y position using sorl_thumbnail
Python 3 and Django 1.11.15 Hi, I'm using a plugin which returns an x and y position from an image besides usual image dimensions (width and height). I'd like to crop this image with sorl_thumbnail in Python using x and y position (like image cover on Facebook). I think there is a function, maybe like cropbox(), but I don't understand how it works. Please someone can help me, giving me an example of using this function or another solution to crop an image with these data. Thanks to all. -
Django class field in if statement
I currently have two different types of user 'Lecturer' and 'Student'. In the html I am trying to create an if statement that only applies if the user is equal to one or the other. I have created this in the models.py class (everything else works) class UserProfile(models.Model): USER_TYPE_CHOICES = ( ('Student', 'Student'), ('Lecturer', 'Lecturer'), ('Admin', 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) type_user = models.CharField(max_length=20, default='s',choices=USER_TYPE_CHOICES) The problem is the if statement in the HTML does not seem to be printing anything {% if user.userprofile.type_user == 'Lecturer' %} <p>Lecturer</p> {% elif user.userprofile.type_user == 'Student' %} <p>Student</p> {% endif %} Please go easy, I am new to Django -
How to change instance in Django with hyperlinks?
I have a problem with Django. I want to change a specific field of a model with an hyperlink but I don't know how to do. I tried this but it makes nothing. views.py: def sGiocatore(request, giocatore_id): item = get_object_or_404(Giocatore, pk=giocatore_id) item.fantasquadra=None #or something else return redirect('/sondaggio/fantasquadre') urls.py: path('svincola/<int:giocatore_id>/', views.sGiocatore, name='s_player'), forms.py: class EditGiocatoreForm(forms.ModelForm): class Meta: model = Giocatore fields = ['fantasquadra'] lista.html: {% for fantasquadra in elenco_fantasquadre %} <p><b>{{ fantasquadra.nome_fantasquadra }}:</b></p> <table id="customers"> {%for giocatore in elenco_giocatori%} {% if giocatore.fantasquadra.nome_fantasquadra == fantasquadra.nome_fantasquadra %} <tr><th>Nome</th><th>Cognome</th><th>N° Maglia</th><th>Squadra</th> <th>Ruolo</th><th>Svincola</th></tr> <tr><td>{{ giocatore.nome_giocatore }}</td> <td>{{ giocatore.cognome_giocatore }}</td> <td>{{giocatore.numero_maglia}}</td> <td>{{giocatore.squadra.nome_squadra}}</td> <td>{{giocatore.ruolo.ruolo}}</td> <td><a href="/sondaggio/svincola/{{giocatore.id}}">Svincola</a></td></tr> {% endif %} {% endfor %} </table> {% endfor %} -
Several labels in for loop
I'm pretty new in programming and I did the Django tutorial 'Writing your first Django app'. Now I want to make some changes to this app and I do not really know how to do it. I want to set several labels with different images for each choice.id in the following input for loop: {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> I'd really appreciate some help about this. Thanks! -
Django Sharing Large File Repository Between Development and Production
I'm trying to develop a Django application that will eventually serve a large media file repository (10's to 100's of GB) that would ultimately be stored on B2 or S3 instead of locally on the server. For application related static content, I think I understand that you will have a /static/ in your application tree, and a /static/ in your web server tree. When you run python manage.py collectstatic the files are compared, and the web server file tree is updated based on the application file tree. Since these would ultimately be uploaded by a user, should I instead be thinking of the MEDIA_ROOTand MEDIA_URL settings? These would then be staging areas prior to preparation and upload to B2 or S3. I've checked these out: Identical and simple way of serving static files in development and production - is it possible? Django: Deploying static files in production environment serving django media (user uploaded) files in production Serve media files with a static service. Dotcloud and I feel like they are probably starting down the right path, but there is minimal discussion so I don't know the alternatives. Are there other approaches I should consider? -
Unable to pass model to context
I'm trying to pass a single model, and a list of models with the same "document_title" to my ModelDetailView template. The code for the views.py section is class DocumentDetailView(generic.DetailView): model = Document def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["doc_list"] = Document.objects.filter(model.document_title).order_by('revision_number') return context I have tried passing the model into the get_context_data method, but that only produces other errors. I'm not sure if I'm going about this the correct way, but any ideas would greatly help. -
django autocomplete light to return only values
I'm using django autocomplete light and from a foreignkey I only need a concatenated value but I get a dictionary back in my select2.My Form looks like this: class BasecampForm(forms.ModelForm): class Meta: model = Basecamp fields = ('name', 'abbr', 'email', 'type', 'sggl') widgets = { 'sggl': autocomplete.ModelSelect2( url='sgga_piped_adresses', attrs={ 'id': 'sggl', 'class': 'form-control m-select2 form-control-sm', 'placeholder': 'Start typing', 'data-minimum-input-length': 3 } ) } def __init__(self, *args, **kwargs): super(BasecampForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'id': 'name', 'class': 'form-control m-input form-control-sm'}) self.fields['abbr'].widget.attrs.update({'id': 'abbr', 'class': 'form-control m-input form-control-sm'}) self.fields['type'].widget.attrs.update({'id': 'type', 'class': 'form-control m-input form-control-sm'}) self.fields['email'].widget.attrs.update({'id': 'email', 'class': 'form-control m-input form-control-sm', 'type': 'email'}) My class view: class AddressAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if self.q: return Sggl.objects.piped_addresses_contains(search_value=self.q) else: return Sggl.objects.none() def get_result_value(self, result): value = result['piped_address'] return value My queryset: def piped_addresses_contains(self, search_value): qs = self.annotate(piped_address=Concat('street', Value(' '), 'country_code', Value('-'), 'postal_code', Value(' '), 'city')).values('piped_address').distinct() qs = qs.filter(Q(postal_code__startswith=search_value) | Q(street__icontains=search_value) | Q(city__icontains=search_value)) return qs When the select2 field is populated the shown values are like: {'piped_address': 'Name of the street'} -
Addition of functions in django-admin copying selected objects and introducing changes
It tries to add a function that copies objects and adds changes to the designated fields. admin.py def duplicate_event(modeladmin, request, queryset): for object in queryset: object.id = None object.save() duplicate_event.short_description = "Duplicate selected record" this is my 'admin.py' function. However, when he tries to make changes to the designated fields, he gets an error like 'Can not assign must be an instance' def duplicate_event(modeladmin, request, queryset): for object in queryset: object.id = None object.id = 'MO' #assigning the value of mo object.save() duplicate_event.short_description = "Duplicate selected record" models.py class Time(models.Model): day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE) compartment = models.CharField(max_length=11) free_or_no = models.BooleanField(default=None) time_equivalent = models.IntegerField() def __str__(self): return self.compartment class DayTime(models.Model): day_of_week = models.ForeignKey(WorkTime, on_delete=models.CASCADE) day_name = models.CharField(max_length=30) full_time = models.BooleanField(default=None) def __str__(self): return self.day_name How to correctly assign the selected object? any help will be appreciated. -
Accesing list in request.get
I'm having difficulties checking on the request.GET parameters in my Django template. django.template.context_processors.request is enabled so I can access request.GET. With the following GET parameters in my URL: ?floor=1&floor=2&building=1, I'm trying to do something like the below: {% if 1 in request.GET.floor %}IN{% else %}OUT{% endif %} I would expect this to return IN. However, OUT is displayed. When diving in more detail: {{ request.GET }} {{ request.GET.floor }} {{ request.GET.urlencode }} Following is returned: <QueryDict: {'building': ['1'], 'floor': [1, 2]}> 2 building=1&floor=1&floor=2 So it looks like my list of [1, 2] for 'floor' is reduced to the last element ('2'). What's the best way to check on the full list? -
Issues in django migrations
I ran into a difficult problem related to Django migrations and searching for answer I created few database models and inserted data on those models by using migrations file Example Model : migrations.CreateModel( name='User', fields=[ ('user_id', models.CharField(max_length=256)), ('name', models.CharField(max_length=256)), ], ) Example Data: user = User(user_id="DEV", name="dev") user.save() user = User(user_id="STAGE", name="stage") user.save() Now i add an ForeignKey in above table say address with some default value and its working fine locally But, If any new user want to pull as a fresh repo, he is getting issues in running migrations as my first migrations file will have hard-coded users table data with out newly added ForeignKey on it Please help me on this -
Django: How to handle exception when the database is down/cannot connect?
We're having a problem on a django application we're developing. Occasionally, the database goes down/has too many connections, etc and Django continuously raises exceptions. How can we catch these exceptions and redirect the user to an error page? -
Django ForeignKey accept two models
I'm working on this big project with Django and I have to update the database. I have to add another table which will replace another later. So I want to add in a model the possibility to have a field where I can have a model representing the ode table OR a model for the new one. Here is the code of the old model: class Harvests(models.Model): ident_culture = models.IntegerField(primary_key=True) intitule_culture = models.CharField(max_length=50, blank=True) nom_fertiweb = models.CharField(max_length=50, blank=True, null = True) affichage_quintaux_tonne = models.CharField(max_length=1, choices=RENDEMENT_CHOICES, default = 'T') type_culture = models.ForeignKey("TypeCulture", null=True) slug = models.SlugField(null=True, blank=True) image = models.ImageField(upload_to = 'images_doc_culture/', null=True, blank = True) affichage = models.BooleanField(default = True) class Meta: verbose_name = "Liste - Culture" verbose_name_plural = "Liste - Cultures" ordering = ['intitule_culture'] def __str__(self): return self.intitule_culture def label(self): return self.intitule_culture or '' @classmethod def get_choices(cls): choices = [('', corp.EMPTY_CHOICE_LBL)] c_category_lbl, c_category = '', [] for item in cls.objects.all(): choices.append((item.pk, item.intitule_culture)) return choices And there is the code od the new one I created: class Crops(models.Model): intitule_culture = models.CharField(max_length=75, blank=True) affichage_quintaux_tonne = models.CharField(max_length=2, choices=RENDEMENT_CHOICES, default = 'T') type_culture = models.ForeignKey("TypeCulture", null=True) ident_culture = models.IntegerField(primary_key=True) affichage = models.BooleanField(default = True) id_marle = models.IntegerField(null=True) class Meta: verbose_name = "Liste - … -
Issues With GSPREAD and Windows Server
I have GSpread working fine locally, but I am getting a 500 error on the server. I am specially getting an error on this line: client = gspread.authorize(creds) In my IIS logs I am receiving a 500 0 0 2734 error. Any ideas? -
I want to just restrict Django OAuth Toolkit for some function in a class
I want to just restrict Django OAuth Toolkit for some function in a class. for registration function we don't need to check authentication. its for public. so I have a class called USERS : have methods i.e i) registration ii)login iii)check_orders etc. I want to just restrict or disabled authentication for registration and login. -
How to convert orderdict into json in python?
How to convert below orderedict into regular json ? in python? [OrderedDict([('ins_short_name', 'MI'), ('beneficiary', []), ('benefit', 65), ('pcp', []), ('benefit_rates', 216), ('added_dependent', []), ('removed_dependent', []), ('ins_name', 'Medical Insurance'), ('plan', {'carrier_logo': 'How to create a DateTime equal to 15 minutes ago?', 'plan_type': 'HMO', 'creation_time': '2019-02-11T06:21:21.743369Z', 'plan_info_details': '', 'rx_coverage': '11', 'id': 65, 'co_pay': '11', 'contribution_interval': None, 'updation_time': '2019-02-11T06:21:21.743808Z', 'benefit_display_name': 'Mi1 HMO', 'carrier': 1, 'status': False, 'carrier_name': 'NHP', 'rx_information': None, 'voluntary': False, 'deductible': '11`', 'hsa_qualified_wrap_plan': False, 'benefit': 65, 'terms_and_conditions': None, 'maximum_contribution': None, 'hsa_qualified_base_plan': False, 'primary_care_physician': False, 'plan_info': ''}), ('dependent', []), ('questions', [OrderedDict([('question', 1), ('question_type', 'radio'), ('identifier', 'Q1'), ('ref', [Decimal('1.00')])]), OrderedDict([('question', 4), ('question_type', 'plan'), ('identifier', 'Q4'), ('ref', [Decimal('216.00')])])])]), OrderedDict([('ins_short_name', 'AI'), ('beneficiary', [OrderedDict([('id', 365), ('first_name', 'rer'), ('last_name', 'ere'), ('relation', 'Spouse'), ('other_relation', None), ('_type', 'Primary'), ('percentage', '100'), ('benefit', 66), ('enrollment', 357), ('creation_time', '2019-02-14T12:04:00.676078Z'), ('updation_time', '2019-02-14T12:04:33.475164Z')])]), ('benefit', 66), ('pcp', []), ('benefit_rates', None), ('added_dependent', []), ('removed_dependent', []), ('ins_name', 'Ancillary Insurance'), ('plan', {'carrier_logo': 'How to create a DateTime equal to 15 minutes ago?', 'plan_type': 'Other', 'creation_time': '2019-02-11T06:24:32.322178Z', 'plan_info_details': '', 'rx_coverage': '', 'id': 66, 'co_pay': '', 'contribution_interval': None, 'updation_time': '2019-02-11T06:24:32.322541Z', 'benefit_display_name': 'Ai name', 'carrier': 1, 'status': False, 'carrier_name': 'NHP', 'rx_information': None, 'voluntary': True, 'deductible': '', 'hsa_qualified_wrap_plan': False, 'benefit': 66, 'terms_and_conditions': None, 'maximum_contribution': None, 'hsa_qualified_base_plan': False, 'primary_care_physician': False, 'plan_info': ''}), ('dependent', … -
Static files with Docker when only Nginx is on host system
I have Nginx on my host machine (Ubuntu server). How should I set up static files when using Docker? version: '2' services: postgres: image: postgres:9.6 redis: image: "redis:alpine" web: &django restart: always environment: - DJANGO_SECRET_KEY=local image: web build: context: . dockerfile: ./compose/production/web/Dockerfile command: /gunicorn.sh depends_on: - postgres - redis links: - redis ports: - "8083:5000" In another project (with no Docker) I have this setting in sites-enabled/mysite: location /static/ { root /home/myproject; } -
How to load a django contrib app without modifying directly the templates of the project
I have built a django app, which when enabled (from the settings.py), can be accessed by the main menu of the project. In order to check if the app is enabled, I use this snippet in one of the templates: {% if 'my_project.contrib.edit_app' in INSTALLED_APPS %} <a class="btn btn-danger btn-block btn-xs" href="{% url "display_data" resource.service_typename %}">{% trans "Edit App" %}</a> {% elif 'my_project.contrib.edit_data' not in INSTALLED_APPS %} <a class="btn btn-default btn-block btn-xs" href="{% url "new_app" %}?layer={{resource.service_typename}}&storeType={{resource.storeType}}">{% trans "New App" %}</a> {% endif %} Apparently is not a good practice to "leak" into the core code, code of contrib apps. What would be a good method to delegate this to the application itself? -
Django REST framework: How can I tell API user identity from mobile app?
I'm really new to creating API. I was successful registering with the web app from mobile app but when I try to get the data which is associated with the user, API returns 403. It means API cannot recognize the user from mobile app. How can I tell the user's identity from mobile app (or other interface)? Here is view I am trying to connect. class MyAccountDetail(generics.RetrieveUpdateDestroyAPIView): queryset = CustomUser.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) # in case the user is not logged in def get_object(self): return self.request.user urls.py path('api/v1/users/my_account', views.MyAccountDetail.as_view()), I'm log in via Google using django-rest-auth. It returns key when I pass access token to the endpoint. What is key used for? -
Django: How to get User model's fields instead of select list in Employee form?
I'm working on an application and I'm stuck in the very beginning. Please help me out here. models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=False) designation = models.ForeignKey(Designation, on_delete=models.CASCADE, null=False) User is from django.contrib.auth.models views.py class EmployeeCreateView(LoginRequiredMixin, generic.CreateView): model = Employee fields = '__all__' success_url = reverse_lazy('core:view-employees') def form_valid(self, form): """If the form is valid, save the associated model.""" self.object = form.save(commit=False) self.object.company = self.request.user.company self.object.save() form.save_m2m() return super().form_valid(form) employee_form.html <form action="{% url 'core:add-employees' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" class="bnt btn-small"> </form> rendered html form Here's the problem. Instead of User being a select list, I want fields of User model, i.e. username, email, password etc, while the Designation should remain as the select list. Thanks in advance. -
Django edit Form doesn't save
I'm a django beginner and i have a little problem. I made a form for create the model "FantaSquadra", and this works. Then i made a form for edit the model and when i press the submit button it doesn't do anything. Can someone help me? urls.py: path('add/fantasquadra/', views.addFantaSquadra, name='creazione_fanta'), path('edit/fantasquadra/<int:fantasquadra_id>/', views.editFantaSquadra, name='edit_fanta'), views.py: def addFantaSquadra(request): elenco_fantasquadre = FantaSquadra.objects.all() if request.method == "POST": form = NewFantaSquadraForm(request.POST) if form.is_valid(): fanta_item=form.save(commit=False) fanta_item.save() else: form = NewFantaSquadraForm() return render(request, 'sondaggio/fantasquadre.html', {'form': form}) def editFantaSquadra(request, fantasquadra_id): item = get_object_or_404(FantaSquadra, pk=fantasquadra_id) form = NewFantaSquadraForm(request.POST or None, instance=item) elenco_fantasquadre = FantaSquadra.objects.all() if form.is_valid(): form.save() return render(request, 'sondaggio/fantasquadre.html', {'form': form}) forms.py: class NewFantaSquadraForm(forms.ModelForm): class Meta: model = FantaSquadra fields = ['nome_fantasquadra','proprietario'] fantasquadre.html <html> <h1>Scrivi il nome della tua fantasquadra</h1> <form method="post"> {% csrf_token %} {{ form }} <button type="submit"><a href="/sondaggio/">Submit</a></button> </form> </html> -
serverselectiontimeouterror mongodb docker-compose service
I am use docker-compose to run django service,including django service,mongo service.I use service name of mongo to configure django.Unfortunately,it throw "pymongo.errors.ServerSelectionTimeoutError: mongo:27017: [Errno 111] Connection refused" -
How do you see what an http request contains
I'm using a django framework for my assignment. I need to view what an http request object contains. print(request) is obviously not working. If i can see the object like in a json structure it would've been a huge help to understand what it would look like and what are the values it contains.