Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select option should not reset after refreshing the page
I'm trying to display list of candidates who took the test. There's a select tag which is used to display the hiring status. There's a dropdown menu against every candidate. I want the dropdown value to be saved to the DB and everytime I refresh the page open the project, that same dropdown value should be displayed which was saved in DB. Here's my code HTML <td> <form method="POST"> <select class="hiring-status" id="hiring" name="hiring_status" > <option selected disabled hidden value="shared">Test Shared</option> <option value="completed">Test Completed</option> <option value="under_review">Test Under Review</option> <option value="hr">HR Round</option> <option value="bg-check">Background Check</option> <option value="technical">Technical Round</option> <option value="assignment">Assignment Given</option> <option value="management">Final Round (Management)</option> <option value="hired">Hired</option> <option value="rejected">Rejected</option> </select> </form> </td> views.py def hiring_status(cls,request :HttpRequest): if request.method=="POST": hiring_status=request.POST('hiring_status') hiring_status.save() return render(request,'pages/test/list.html') else: return render(request, 'pages/test/list.html') models.py class Hiringtatus(enum.Enum): test_completed=1 test_under_review=2 hr_round=3 background_check=4 technical_round=5 assignment_given=6 final_Round=7 hired=8 rejected=9 class Test(BaseModel): hiring_status = Column(ChoiceType(Hiringtatus, impl = Integer())) I added below code but it works for the first dropdown menu and if I close the server/output window, it goes back to default value. var selectedItem = sessionStorage.getItem("SelectedItem"); $('#hiring').val(selectedItem); $('#hiring').change(function() { var dropVal = $(this).val(); sessionStorage.setItem("SelectedItem", dropVal); }); This is a sample output image -
NoReverseMatch when using NamespaceVersioning in django
I'm trying to implement versioning in django. My project urls.py looks like: url(r"^v1/sites/", include((site_urls, "sites"), namespace="v1")), url(r"^v2/sites/", include((site_urls, "sites"), namespace="v2")), in my settings/base.py I added: REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", "DEFAULT_VERSION": "v1", } This works for the default version (v1). If I run a test class, it works. But when I try to test a v2 version test like: def test_get_all_sites_admin_version_2(self): self.client.force_login(self.admin_user) url = reverse("v2:admin-site-list") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) I got following error: django.urls.exceptions.NoReverseMatch: Reverse for 'admin-site-list' not found. 'admin-site-list' is not a valid view function or pattern name. Do I need to configure something else? -
Python: How to stream audio from firebase cloud storage
I know this question has been asked multiple times but they all refer to a different platform in a different language. I'm trying to achieve audio streaming via my django(Web framework) application, think of this app as some sort of 'Spotify' or 'Soundcloud'. Ive also heard that firebase Storage doesn't support special media streaming protocols, such as RTSP, so does this mean that streaming is impossible? -
Automating Django Deployment
We have a team working on a product (using Python/Django). Every time, a feature is completed or a bug is resolved, it is first tested locally, then pushed to the staging server. We (the developers) then have to ssh into the server, take the latest pull, run some migrations, restarting our daemon script and then finally, restart the server (we're using Apache). If there are some updates in the requirements.txt, we then have to install it again so that our virtual environment is updated. We also have QA Engineers but for most part, they are manual testers, they also do Automated testing but for now that's rare. I want to automate this whole process i.e once the changes are pushed, a pull is taken on the server (in our case it's staging server, will also include Production server), scripts are run and Apache is restarted. I'm looking for recommendations on which tool/methodology to use that will help achieve my goal in the longer run? -
Failure to remove the CSS effect when deleting the CSS file in Django
I created a simple Django project and put some stuff on the index page and linked a CSS file to it and it works. When I delete the CSS file, its effect does not disappear unless I remove the link from html file. I wanted to know what is the reason. Thank you. -
How to pass StreamingHttpResponse from django to page with template?
Got stuck with below code. New to django. I want to stream the video with django framework to the webpage using StreamingHttpResponse by using template. I tried bellow code. return StreamingHttpResponse(gen(VideoCamera()) but the problem with it is the entier page is shwoing the video. I want to pass the video from django to template for a "p" tag or "img" tag. Thanks in advance. -
Queryset Django
Here is my view in Django: class QuerySet1(generics.ListAPIView): """Количество приемов у каждого врача""" permission_classes = [permissions.AllowAny, ] def get_queryset(self): app_num = Appointment.objects.values('record__doctor').annotate(amount=Count("id")) app_num = list(app_num) print(app_num) return app_num serializer_class = QuerySet1Serializer and this is serializer: class QuerySet1Serializer(serializers.Serializer): amount = serializers.IntegerField() doctor = serializers.CharField(source='record__doctor') class Meta: model = Appointment fields = ("amount", "doctor") When I run code it gives me next error AttributeError: 'dict' object has no attribute 'pk' Help please! How can I solve it? Thanks -
TypeError: Field 'id' expected a number but got <User: >
I'm using django and recently remade my Posts Model in models.py, however whenever i try and make migration i get the following error. Thanks in advance! : Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: Applying blog.0006_post_author...Traceback (most recent call last): File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'User' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 110, in … -
two unrelated models in one serializer django rest framework
I have tried a few different ways to include two unrelated models in one serializer to use in DRF api response. This is the latest of tries below, which doesn't work. I'm trying to include those two values (enable_hourly_rate / vacancy_number) from Tenant model which are under TenantAppUnitExpandedSerializer to TenantAppUnitSerializer. How to do this the proper way? Thank you in advance for any help. Code so far: class TenantAppUnitExpandedSerializer(serializers.ModelSerializer): class Meta: model = Tenant fields = ( 'enable_hourly_rate', 'vacancy_number', ) class TenantAppUnitSerializer(TenantAppUnitExpandedSerializer): shift_editor_enable_hourly_rate = serializers.SerializerMethodField() module_vacancy_number = serializers.SerializerMethodField() class Meta: model = Unit fields = ( 'id', 'unit_name', 'city', 'phone', 'enable_hourly_rate', 'vacancy_number' ) -
Django resize and crop picture form errors with AWS S3
I'm trying to create a crop and resize modal on my website so the user is able to resize and crop its picture to the square format I need. I am using this tutorial. Unfortunately, the tutorial does not work well with AWS S3 media files servers (I am hosting my website on Heroku so there is no way I can host my files on their dyno). At the moment, my upload template works (with the modal that resizes pictures) but my form raises an error that I understood to be linked to S3Boto3 : Server error when uploading the resized and cropped picture 2020-07-06T12:50:28.497706+00:00 app[web.1]: <PIL.Image.Image image mode=RGB size=408x407 at 0x7FCE8ED04DD8> 2020-07-06T12:50:28.497798+00:00 app[web.1]: resized.jpg 2020-07-06T12:50:28.632718+00:00 app[web.1]: Internal Server Error: /selling/articles/s/gouda 2020-07-06T12:50:28.632722+00:00 app[web.1]: Traceback (most recent call last): 2020-07-06T12:50:28.632758+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner 2020-07-06T12:50:28.632759+00:00 app[web.1]: response = get_response(request) 2020-07-06T12:50:28.632760+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response 2020-07-06T12:50:28.632761+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2020-07-06T12:50:28.632761+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response 2020-07-06T12:50:28.632762+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2020-07-06T12:50:28.632762+00:00 app[web.1]: File "/app/selling/decorators.py", line 12, in wrapper 2020-07-06T12:50:28.632762+00:00 app[web.1]: return function(request, *args, **kw) 2020-07-06T12:50:28.632763+00:00 app[web.1]: File "/app/selling/views.py", line 104, in create_update_article 2020-07-06T12:50:28.632763+00:00 app[web.1]: picture = picture_form.save() 2020-07-06T12:50:28.632763+00:00 app[web.1]: File … -
Django problem with auto SlugField on two class in models
I have problem with add auto SlugField. When i will try add some post in panel admin, its ok. Because i type slug manually. But if i try use form to create new post in templates is not added automatically. -
Passing id on views
I would like to pass the id of an organization, in a view function that doesn't pass an id. Views.py def OrgForm_view(request): if request.method == 'POST': post=Organization() post.orgname= request.POST.get('name') post.address = request.POST.get('address') post.save() return redirect('/results_view/') else: return render(request,'index.html') def results_view(request, organization_id): orgz = Organization.objects.get(id=organization_id) context = {'orgz': orgz} return render(request, "results.html", context) Urls.py path('OrgForm/', OrgForm_view, name="OrgForm"), path(r'results_view/<int:organization_id>/', views.results_view, name="results_view"), -
how to work with django and javascript modal
i'm working on a projects for a mobile store which working with IMEI of mobiles each single mobile has its own unique imei , now when the admin add new mobile in MobileStorage for example quantity= 20 mobile iphone11X have 20 different IMEI's , i want to allow the admin whenever he add new mobile and then select the quantities (20) then extra fields will be 20 , if he filled 10 in quantity field extra fields for IMEI will be 10 , i did it in front end using javascript but i dont know how to add imeifield to the js code ? this is my models.py class Mobile(models.Model): mobile = models.CharField(max_length=50,unique=True) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Imei(models.Model): imei = models.CharField(max_length=50,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) i have make inlineformset whenever i wanted add a new MobileStorage then at the same time i add its IMEI's ! my forms.py class MobileStorageForm(forms.ModelForm): mobile = forms.ModelChoiceField(queryset=Mobile.objects.all(),empty_label='mobiles') class Meta: model = MobileStorage fields = [ 'mobile','quantity' ] class ImeiForm(forms.ModelForm): class Meta: model = Imei fields = ['imei'] MobileStorageInlineFormSet = inlineformset_factory( MobileStorage,Imei,form=ImeiForm,fields=('imei'),extra=1,can_delete=False ) and this is my views.py class CreateMobileStorageView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = MobileStorage form_class = MobileStorageForm template_name = 'mobile/add_storage.html' def get_context_data(self,*args,**kwargs): … -
Django for loop and bootstrap tab list
I have a vertical tab list on the left of my page with names and when you click on a tab, the right side of the tab is detailed information of the name you have clicked. my html code looks like <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <title>Responsive vertical tabs for Bootstrap 4</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" /> <!-- Vertical tabs CSS --> <link rel="stylesheet" href="b4vtabs.min.css" /> </head> <body> <div class="py-3 text-center"> <h1>Responsive vertical tabs for Bootstrap 4</h1> <p class="lead">-</p> </div> </div> <div class="container"> <div class="row"> <div class="container"> <hr /> </div> </div> <div class="row"> <div class="col-md-12"> <h3>Responsive vertical tabs for Bootstrap 4</h3> <hr /> </div> </div> <div class="row"> <div class="col-md-1"> <ul class="nav nav-tabs left-tabs sideways-tabs"> <li class="nav-item"> <a class="nav-link active" href="#lorem-sleft" data-toggle="tab">Lorem</a> </li> <li class="nav-item"> <a class="nav-link" href="#ipsum-sleft" data-toggle="tab">Ipsum</a> </li> <li class="nav-item"> <!-- use the title attribute to show a tooltip with the full long name in case the tab is trucated--> <a class="nav-link" href="#llanfairpwllgwyngyll-sleft" data-toggle="tab" title="Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch" >Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch</a > </li> </ul> </div> <div class="col-md-11"> <div class="container"> <div class="tab-content"> <article class="tab-pane container active" id="lorem-sleft"> <h1>Lorem</h1> <section> Lorem ipsum dolor sit amet, consectetur adipiscing … -
Reverse for 'edit_profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['profile/(?P<pk>\\d+)/edit/$']
from django.views.generic import (TemplateView, CreateView, ListView, UpdateView, DetailView, FormView) from django.contrib.auth.models import User, auth from pics.forms import UserCreationForm, UserInfoForm, PostForm from pics.models import Profile, Post from django.contrib.auth.decorators import login_required from django.utils import timezone from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect, render, get_object_or_404, reverse from django.urls import reverse_lazy from pics.forms import userForm class SignUp(CreateView): form_class = userForm template_name = 'pics/signup.html' success_url = reverse_lazy('login') class LoginPage(TemplateView): template_name = 'pics/login_signup_page.html' class UploadPage(CreateView, LoginRequiredMixin): login_url = '/login/' model = Post form_class = PostForm template_name = 'pics/upload_form.html' success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super(UploadPage, self).get_context_data(**kwargs) context['profilo'] = Profile.objects.all().order_by('-date') # Add any other variables to the context here ... return context @login_required def post_publish(request): Post.uploadPost() return redirect('home') class ProfilePage(FormView, LoginRequiredMixin): login_url = '/login/' model = Profile form_class = UserInfoForm template_name = 'pics/user_form_page.html' success_url = reverse_lazy('pics:user') def form_valid(self, form): return super().form_valid(form) @login_required def profile_publish(request, pk): profilo = get_object_or_404(Profile, pk) profilo.save_profile() return redirect('pics:user') class ProfilePageUpdate(UpdateView, LoginRequiredMixin): login_url = '/login/' model = Profile context_object_name = 'profilo' form_class = UserInfoForm template_name = 'pics/user_form_page.html' class UserPage(ListView, LoginRequiredMixin): login_url = '/login/' queryset = Profile.objects.all() context_object_name = 'profilo' model = Profile template_name = 'pics/user.html' def get_context_data(self, **kwargs): context = super(UserPage, self).get_context_data(**kwargs) context['posts'] = Post.objects.all().order_by('-date') return context def get_queryset(self): return Profile.objects.filter(date__lte=timezone.now()).order_by('-date') … -
Django for loops doesn't work in Template
So i'm using ListView in django and im trying to display database content using for loops but it doesn't show anything(blank) this is a piece of my views from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView) class DraftListView(LoginRequiredMixin,ListView): template_name = 'blog/post_draft_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') my template {% for post in post_list %} <div class="row"> <div class="col-md-4"> <div class="post"> <p><a href="{% url 'blog:post_detail' pk=post.pk %}">{{post.title}}</a></p> <p class="date">created: {{post.created_date}}</p> <p>{{post.text|truncatechars:200|safe}}</p> </div> </div> </div> {% endfor %} and models class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) thumb_pic = models.ImageField(upload_to='thumb_pic/',blank=True) title = models.CharField(max_length=200) text = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("blog:post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title -
TypeError: memoryview: a bytes-like object is required, not 'bool'
I am following a tutorial to learn django and rest framework. In this tutorial vagrant is also used. When I'm trying to create super user by using create superuser command (From vagrant environment), I get following error: TypeError: memoryview: a bytes-like object is required, not 'bool' Why I'm getting this error? -
Django serve zipped GeoDataFrame shapefile from memeory as download
I have a Django GIS-related application where users can download shp files. I have the geopandas GeoDataFrame object. I can easily convert it to a zipfile and then read the zipfile to the user when they want to download it: from django.http import HttpResponse import geopandas as gpd import shapely import os from zipfile import ZipFile def download_shp_zip(request): # just some random polygon geometry = shapely.geometry.MultiPolygon([ shapely.geometry.Polygon([ (0, 0), (0, 1), (1, 1), (1, 0) ]), shapely.geometry.Polygon([ (2, 2), (2, 3), (3, 3), (3, 2) ]), ]) # create GeoDataFrame gdf = gpd.GeoDataFrame(data={'geometry':geometry}, crs='epsg:4326') # some basename to save under basename = 'basename' # create folder for this session os.mkdir(f"local_folder/{basename}") # export gdf to this folder gdf.to_file(f"local_folder/{basename}/{basename}.shp") # this file now contains many files. just zip them zipObj = ZipFile(f"local_folder/{basename}.zip", 'w') # zip everything in the folder to the zip for file in os.listdir(f"local_folder/{basename}"): zipObj.write(f"local_folder/{basename}/{file}") # create zip zipObj.close() # now delete the original files that were zipped shutil.rmtree(f"local_folder/{basename}") # now we can server the zip file to the user filename = f'local_folder/{basename}.zip' # check if file exists (just in case) try: fsock = open(filename, "rb") except: return HttpResponse(f"File '{basename}' Does Not Exist!", content_type='text/plain') # create response response = HttpResponse(fsock, … -
Django Rest Framework : django.core.exceptions.ValidationError: ["'62f32c11-c04f-44a3-8f24-13b274a20ce6' is not a valid UUID."]
I am using UUID in PostgreSQL DB for the applications. The application works fine. But, after some time, when I try to log in, it shows an error django.core.exceptions.ValidationError: ["'62f32c11-c04f-44a3-8f24-13b274a20ce6' is not a valid UUID."]. Here, UUID I Cross checked with the database and seems exact. The issue goes away after some time or I restart the apache server. I have tried all the possible combinations and nothing works. Also, tried solutions from StackOverflow threads mentioning the same issue. Nothing works. [wsgi:error] [pid 9630:tid 139896115861248] File "/var/www/backend/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2330, in to_python [wsgi:error] [pid 9630:tid 139896115861248] params={'value': value}, [wsgi:error] [pid 9630:tid 139896115861248] django.core.exceptions.ValidationError: ["'62f32c11-c04f-44a3-8f24-13b274a20ce6' is not a valid UUID."] -
AttributeError at /customer/1/ 'customer' object has no attribute 'order_set'
I am trying to access the orders of each customer and i approached it this way: def Customer(request, pk): Customer = customer.objects.get(id=pk) orders = Customer.order_set.all() order_count = orders.count() context = { 'orders': orders, 'customer': Customer, 'order_count': order_count, } return render(request, 'Inventory_Management/customer.html', context) on the youtube the man said that you can access the orders related to the customer by using the orders model name which in my case is 'order' and then add _set i did that and when i try to view the customer now i get this error: AttributeError at /customer/1/ 'customer' object has no attribute 'order_set'. related models class order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) order_head = models.ForeignKey(order_header, blank=False, null=True, on_delete=models.SET_NULL) items = models.ForeignKey(item, blank=False, null=True, on_delete=models.SET_NULL) Quantity = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True, null=True) total = models.CharField(max_length=100) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return 'Order Customer: {self.order_head.Buyer}'.format(self=self) class customer(models.Model): name = models.CharField(max_length=12, blank=False) phone = models.CharField(max_length=12, blank=False) email = models.CharField(max_length=50, blank=False) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name related view def Customer(request, pk): Customer = customer.objects.get(id=pk) orders = Customer.order_set.all() order_count = orders.count() context = { 'orders': orders, 'customer': Customer, 'order_count': order_count, } return render(request, 'Inventory_Management/customer.html', context) … -
How to optimize django and xlsxwriter export
I have a piece of code that take 7 hours to process an excel file. I have a table Agent, with 400 000 agents in this table. Etablissement table with 200 Etablissements. The goal to my function is to extract ALL agent of this table into a xslx file. I don't succeed to optimize this code, i think i missed something ... I know the thing that take time to process is the link between my Agent table and Etablissement table for example, but i need them in the export. I also added: 'constant_memory': True There is double "for" loop with data from database, i need this :/ filename = "agent.xlsx" workbook = xlsxwriter.Workbook(filename, {'constant_memory': True}) worksheet = workbook.add_worksheet() row = 0 col = 0 titles = ['Matricule', 'Nom', 'Prenom', 'Genre', 'Date de naissance', 'Date entree', 'code statut', 'statut', 'Pourcentage TT', 'categorie emploi', 'Code corps', 'intitule corps', 'code grade', 'intitule grade', 'code metier', 'intituler metier', 'code UF', 'nom UF', 'code pole', 'nom pole', 'lettre budgetaire','Code ANFH', 'territoire', 'region', 'etape','commentaire'] agents = Agent.objects.all() for i, item in enumerate(titles): worksheet.write(row, col + i, item) row += 1 for agent in agents: worksheet.write(row, 0, agent.matricule) worksheet.write(row, 1, agent.name) worksheet.write(row, 2, agent.first_name) worksheet.write(row, 3, … -
Django,error creating new profile modal after user registerion
I am developing a Django website by following a Github repo as mentioned below. When new user signup, it does not create a profile associated with it, when I try accessing the profile, I got response as RelatedObjectDoesNotExist at /accounts/profile/ User has no profile. What might went wrong here ? The following code snippets are from users app of my Django project. apps.py class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=500,null=True,blank=True) phone = models.PositiveIntegerField(null=True,blank=True) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['address','phone'] (git hub repo of following tutorial : https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog/11-Pagination/django_project/users), If you don't know the answer , kindly up vote for more reach. -
Embedding external links using the file:/// protocol in Django
I would like to use Django to link to a file located on a server in a local network. Let's say the server name is \\server When I add a link to a local html test file, it works: <a href="file://///server/subpath/image.jpg">link</a> However, when use the exact same line in a Django template, it does not work. Clicking the link does not do anything. I ran a few checks: Firefox allows me to open the link in a new frame, but does not display the image, even if I hit Refresh. It does however load the image when I click the address bar and press Enter. Chrome does not even let me open the link in a new frame. It displays about:blank#blocked in the title bar if I try. This leads me to believe that this is deliberate behavior by Django, likely a security feature to prevent accidental access to local files. I wonder how Django does this though because when I look at the website's source code, it looks perfectly fine. The links show up as they should and if I copy the source code to a local file everything works as I expect. Can someone clarify whether this is … -
Django NamespaceVersioning example/how to start
I need to implement versioning on our application. I read the django docs about it: https://www.django-rest-framework.org/api-guide/versioning/#namespaceversioning But I find it quite short and incomplete? I started with changing my urls.py in my app as the docs mentioned: re_path(r"^v1/sites/", include(site_urls, namespace="v1")), re_path(r"^v2/sites/", include(site_urls, namespace="v2")), and added this to my settings.base "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", Now I get following error: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. When I add this like: re_path(r"^v1/sites/", include(site_urls, app_name="sites", namespace="v1")), re_path(r"^v2/sites/", include(site_urls, app_name="sites", namespace="v2")), I get the error: TypeError: include() got an unexpected keyword argument 'app_name' Also I want to make sure there is a default version when no version is given. How can I do this? -
How to use factory.LazyAttribute with Faker() functions
I am using factory_boy to build some fixtures in Django. I want to use factory.LazyAttribute to build one attribute based on the condition of another attribute. class MyFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel title = 'My Title' if random() < 0.5 else None description = factory.LazyAttribute( lambda a: factory.Faker( 'paragraph', nb_sentences=1, variable_nb_sentences=False ) if a.title else None) However, this returns a string being <factory.faker.Faker object at 0x000001B10597BB20> rather than executing the correct paragraph generation. Where am I going wrong?