Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "Client class" integration into VS Code
I have had several issues integrating Django testing into VSCode. Finally I succeeded to run most kinds of tests (the trick, it seems, is to run django.setup() before anything else happens, including importing Django modules), but now I am having a problem with Django's client class. I do a simple client.get() and I get a 400 (Bad Request) error from within VSCode. But if I run "python manage.py test" from the CLI the test works! I am completely at a loss as to what is happening... Here is my code. It couldn't be simpler. import logging import django django.setup() from django.test import Client, TestCase # noqa: E402 from django.db import DatabaseError # noqa: E402 logger = logging.getLogger('XXXX.debugger') class WorkflowAPIClient(TestCase): def test_createWorkflow(self): client = Client() resp = client.get('/workflow/') logger.debug(f'After request: {resp.status_code} - {resp.content}') self.assertEqual(resp.status_code, 200) When I run this from the CLI as "python manage.py test" it runs OK (assertEqual succeeds). When I try to run this from the test module of VSCode, it gives a status_code of 400 and thus assertEqual fails. I am using unittest for the VSCode test configuration and it discovers the test files without any problem. -
UTF-8 encoding for xhtml2pdf in Django
I am using xhtml2pdf package to generate a pdf file from an html template in my django application. The pdf file generates correctly (no errors), however, I have encountered a problem with UTF-8 encoding. My generated pdf file, instead of special charactes (PL language), shows black squares. I have gone through almost all solutions available online, but none of them helped. When I am using ReportLab and generate pdf without a template, all seems to be okay. Am I missing something perhaps on the views side? My html template {% load static %} <!DOCTYPE html> <html lang="pl-PL"> <head> <meta charset="UTF-8"> <title>PDF {{obj.orderNumber}}</title> <style> @font-face { font-family: 'Lato'; src: url(https://github.com/google/fonts/blob/master/ofl/lato/Lato-Regular.ttf?raw=True); } * { font-family: 'Lato'; } table { -pdf-keep-with-next: true; } p { margin: 0; -pdf-keep-with-next: true; } p.separator { -pdf-keep-with-next: false; font-size: 6pt; } .bander{ color:brown; font-size:13pt; } </style> </head> <body> <img src="media/logo.jpg" style="height:60px;"> <h2> PLAN ROZKROJU ZLECENIA: </h2> <h1 style="color:#997207;">{{obj.orderNumber}} {{obj.orderName}}</h3> <h2> Naklad: {{obj.orderQuantity}} szt </h2> <h4> Data utworzenia wydruku: {{obj3}} </h4> <div> <table class="table table-bordered" style="text-align: center; padding: 5px;" border="0.2"> <thead class="table-active"> <tr> <th scope="col">Nazwa materialu</th> <th scope="col">Ilosc</th> <th scope="col">Nazwa czesci</th> <th scope="col">Wymiar (mm)</th> <th scope="col">Wymiar 2 (mm)</th> </tr> </thead> <tbody> {% for item in obj2 %} <tr> … -
Django - column of relation already exists - should I use --fake?
I have a Django app using PostgreSQL with tenant_schemas. My DB has been imported from a .sql file, and now I have to run the migrations (with some changes in it, differen than the original DB imported from the .sql). When I do that, I get: django.db.utils.ProgrammingError: column "active_vendor" of relation "analysis_supplier" already exists I've researched this problem, and it looks like some people (on stackoverflow) recommend using --fake for this situation. But according to django docs: --fake Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema. This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly. As I understand, this means that the migration will only be added to the migration table of django, and the SQL code will not be ran. I don't think I want that. Am I misunderstanding it? If so, should I use --fake in my situation? If not, how should I fix … -
How to prevent N+1 queries when fetching ancestors with Django Treebeard?
We are using Django Treebeard's materialized path to model an organizational hierarchy as follows: Now each node in the organizational tree can have multiple tasks: class Organization(MP_Node): node_order_by = ['name'] name = models.CharField(max_length=100) class Task(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) description= models.TextField() Given a list of tasks, we wish to include the full organizational path of each task in the result. How can we achieve this without the need for N+1 queries? Expected result for organization Factory 1 could be for example: Task name Organization Path Task 1 MyCompany/Factory 1/Maintenance Task 2 MyCompany/Factory 1/Operations Task 3 MyCompany/Factory 1 Task 4 MyCompany/Factory 1/Operations -
How to select single entity from multiple entity with maximum value of a field in django?
models.py def return_timestamped_id(): last_unique_id = RMLocation.objects.all().order_by('id').last() if not last_unique_id: return 'RM0001' else: timestamped_id = last_unique_id.unique_id timestamped_id = int(timestamped_id.split('RM')[-1]) width = 4 new_unique_int = timestamped_id + 1 formatted = (width - len(str(new_unique_int))) * "0" + str(new_unique_int) new_unique_id = 'RM' + str(formatted) return new_unique_id class RMLocation(models.Model): warehouse = models.ForeignKey(RMWarehouse, on_delete=models.CASCADE, related_name='l_warehouse') cabinet = models.CharField(max_length=255, blank=True, null=True) rack = models.CharField(max_length=255, blank=True, null=True) shelf = models.CharField(max_length=255, blank=True, null=True) file_name = models.CharField(max_length=255, blank=True, null=True) file_no = models.CharField(max_length=255, blank=True, null=True) unique_id = models.CharField(default=return_timestamped_id, max_length=255, blank=True, null=True) # Auto generated. uuid = models.CharField(max_length=40) record_extension = models.ForeignKey(DocumentExtension, on_delete=models.CASCADE, related_name='rec_ext', blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='record_company') is_ocr = models.BooleanField(default=False) ocr_text_file = models.CharField(max_length=255, blank=True, null=True) is_trashed = models.BooleanField(default=False) trashed_on = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_created_by') updated_at = models.DateTimeField(blank=True, null=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_updated_by') deleted_at = models.DateTimeField(blank=True, null=True) deleted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_deleted_by') def __str__(self): return str(self.id) class Meta: db_table = 'record_location' class RMRecordVersion(models.Model): VER_TYPE_CHOICE = ( ('major', 'major'), ('minor', 'minor') ) record = models.ForeignKey(RMLocation, on_delete=models.CASCADE, related_name='rv_rec') scanned_file_location = models.TextField(blank=True, null=True) size_in_kb = models.FloatField(default=0.0) version_no = models.IntegerField(default=1) version_code = models.CharField(default='1.0', max_length=10) version_type = models.CharField(choices=VER_TYPE_CHOICE, max_length=10, default='major') created_at = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='rv_rm_user', null=True, blank=True) def … -
Merge two or more Many to Many models in Django admin page
How can I add or more Models on one page with Many-to-Many models in Django admin change view page? For example If I have the following models, what could be the best way to add them all on the same change view page : class Course(SoftDeletionModel, TimeStampedModel, models.Model): uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) overview = models.CharField( _('Overview'), max_length=100, null=True, blank=True) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) def __str__(self): return self.title class Meta: verbose_name_plural = "Topics" ordering = ['ranking'] class SubTopic(TimeStampedModel, models.Model): """ Subtopic for the course. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) sub_topic_cover = models.ImageField( _('Sub topic Cover'), upload_to='courses_images', null=True, blank=True, max_length=900) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) course = models.ManyToManyField(Course, related_name='sub_topic', blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Sub topic" ordering = ['ranking'] class Lesson(TimeStampedModel, models.Model): """ Lesson for the sub topic. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) subtopic = models.ManyToManyField(SubTopic, related_name='lessons', blank=True) video_link = models.CharField( _('Video Link'), max_length=800, null=False, blank=False) def … -
Best way to create multiple sqlalchemy order_by statements from django REST
I want to use querystring parameters to set multiple order variants. Lets take a Table with the following columns: id, user_id, amount, date, text And ordering should be a list of dict like [{"amount": "desc"}, {"date": "asc"} ] in the crud-file: def get_multi_by_userid( db_session: Session, *, userid: int, skip=0, limit=1000, ordering ) -> List[Optional[transactions]]: orderstring = "" querystring = """db_session.query(transactions) .filter(transactions.userid == userid ) {} .offset(skip) .limit(limit) .all() """ for i in ordering: orderstring += ".order_by(transactions.{}.{}())".format(list(i.keys())[0],i[list(i.keys())[0]]) querystring.format(orderstring) return (eval(querystring), 200) now to my question: Is there a more elegant (and safer) way? -
Django - What is the benefit of squashing migrations?
So why would we want to squash migrations? I can think of two reasons so far: Cleanup. It is nice to have cleaned up migrations. Faster tests as creating the test database should be faster which is nice for the CI/CD pipeline. Overall it does not seem very important to do.. What do you guys think? -
Multiple Tables for one Django Model
How can I dynamically create multiple tables for one specific model? I have a model (e.g. "Data") and want each user to get a separate database table for this model. There will be between 30 and 40 users, each with about 20 million entries in "Data". So that the database table does not get 800 million rows, I would like to split it. Of course, it is also possible that there will be more in the future Is this still possible with Django ORM? I'm on PostgreSQL Thanks :) -
Getting "AuthToken.user" must be a "User" instance. in django-rest-knox register api and using Custom django user
I'm building a login and signup api with django rest frame work. I created a custom user, and I'm using django-rest-knox library for authentication. I'm getting error "AuthToken.user" must be a "User" instance. Custom User Definition class User(AbstractBaseUser): email = models.EmailField(verbose_name='email_address', max_length=255, unique=True,) full_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) phone_number = PhoneNumberField(region='NG', blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name', 'phone_number'] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.full_name def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin objects = UserManager() Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'full_name', 'email', 'phone_number', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['email'], validated_data['full_name'], validated_data['phone_number'], validated_data['password']) … -
class CustomObtainAuthToken(obtain_auth_token): TypeError: function() argument 'code' must be code, not str
ObtainAuthToken is knwon as obtainauthtoken. enter image description here from rest_framework.authtoken.views import obtain_auth_token class CustomObtainAuthToken(obtain_auth_token): def post(self, request, *args, **kwargs): response = super(CustomObtainAuthToken, self).post( self, request, *args, **kwargs) token = Token.objects.get(Key=response.data['token']) user = User.objects.get(id=token.user_id) userSerializer = UserSerializer(user, many=False) return Response({'token': token.key, 'user': userSerializer.data}) Error: File "D:\project\backend\api\urls.py", line 2, in from api import views File "D:\project\backend\api\views.py", line 31, in class CustomObtainAuthToken(obtain_auth_token): TypeError: function() argument 'code' must be code, not str -
Django - query to sum value atribute from model in frontpage
I have a model class for Courses named "Curs" where i set a field with number of stundets (alocati_curs). When i loop in frontpage to show all the courses existed i show them {% for curs in profil.curs_set.all %} .... Also i can display the numaber of courses {% with profil.curs_set.all.count as total_cursuri %}.... . But i dont't know how to make a query to get the total students (alocati_curs) from all the courses. Please help me :) . Thank you. I tried {% with profil.curs.alocati_curs_set.all.count as total_cursuri %} and {% for curs in profil.curs.alocati_curs_set.all %} but is not working and i think is not correct. -
WebSocket connection to 'wss://...' failed: (Django + Gunicorn + Nginx + Daphne)
I'm getting an error while connecting the websocket. And I have read similar Q&A on stackoverflow but still not working for me. I've been trying all sorts of ways for days but still can't make the connection. This is my mistake The server I use is: Django + Gunicorn + Nginx + Daphne Browser error WebSocket connection to 'wss://mydomain/ws/some_url/' failed: Below is my config on the server Ngnix config: server { server_name ****** mydomain www.mydomain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/django/magi/src/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/magi.thcmedia.vn/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/magi.thcmedia.vn/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }server { if ($host = www.magi.thcmedia.vn) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = magi.thcmedia.vn) { return 301 https://$host$request_uri; } # managed by Certbot server_name 103.221.223.183 magi.thcmedia.vn www.magi.thcmedia.vn; listen 80; return 404; # managed by Certbot } If you need to check any files, please comment below so I can add … -
Django allauth: Linking socail regsitered user to an account which has same email
Here is problem: I allowed user to social login with Google and Github. And both of them have a email scope. And it is possible to both of them have same email. In this kind of situations django redirects to another sign up page I want to connect both users to same account if their emails are same -
There is another cms for django?(not "django CMS") or why i should use django cms?
I own a site that sells WordPress templates. Recently, I was trying to create Django-based templates, which I found after a bit of searching on the Django CMS site. But then I went to install it and figure out how to make a template for it, I just realized Just installing Django CMS is difficult for the simple user, but even for me, the programmer, it is difficult to install. Is there no substitute for it? Or how can I make it easier for my users to install? -
Django Manage.py Vlaidation Error if value exist
i want to create a custom validation, but its not working with this conditions. if self.orange==True and self.mango==True: raise ValidationError( { "pineapple": _("do not need to filled"), "grape": _("do not need to filled") } ) -
Shared Post Doesn't Post Images to the Shared Object In the backend
I am having a had time sharing post with my function, My challenge is when ever i share a post the share images in the original post doesn't post the images to the new post image field, but rather it repost the images in the original share post field and so it makes it not possible to show the shared image! my question why am I getting this effect of post being reposted in the original image field and not the new shared post field! hoping for a solution ? Here is my function for sharing post: def share_post(request, pk): original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, video = original_post.video, shared_on = datetime.now(), shared_user = request.user) new_post.save() form = GroupImageForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) for image in original_post.groupimage_set.all(): new_post = GroupImage(post=original_post, group=original_post.group, shared_user=request.user, image=image.image) new_post.save() return redirect('group:main',original_post.group.pk) else: form = GroupImageForm(request.POST, request.FILES) ctx = {'form':form, 'original_post':original_post} return render(request,'group/share_form.html', ctx) Here is my model for images and post class Post(models.Model): group = models.ForeignKey(GroupEx, on_delete=models.CASCADE, related_name="group_post") username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE ,related_name="group_user") description = models.TextField(max_length=500, blank=True) video = models.FileField(upload_to="group_videos", blank=True) shared_body … -
Convert Django function view to class based view
I do not know how to convert those functions to a class-based view. How to call a filter, add, and remove functions in a class-based view? Should I overwrite functions somehow in the TemplateView? @ login_required def favourite_list(request): new = Post.newmanager.filter(favourites=request.user) return render(request, 'accounts/favourites.html', {'new': new}) @ login_required def favourite_add(request, id): post = get_object_or_404(Post, id=id) if post.favourites.filter(id=request.user.id).exists(): post.favourites.remove(request.user) else: post.favourites.add(request.user) return HttpResponseRedirect(request.META['HTTP_REFERER']) -
How to parse json parallel in django to speed up application
This question is regarding django. How can I parse json and insert them in database in most fastest way possible. Here is the code below identifier = str(uuid.uuid4()) insert = report() insert.id = identifier insert.title = var google_autocomplete_url = "https://google.com/complete/search?client=chrome&q=" insert.null_keywords = ujson.loads(requests.get(google_autocomplete_url+var, headers=headers).text)[1] insert.vs_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+vs", headers=headers).text)[1] insert.versus_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+versus", headers=headers).text)[1] insert.or_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+or", headers=headers).text)[1] insert.and_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+and", headers=headers).text)[1] insert.like_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+like", headers=headers).text)[1] insert.with_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+with", headers=headers).text)[1] insert.near_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+near", headers=headers).text)[1] insert.is_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+is", headers=headers).text)[1] insert.for_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+for", headers=headers).text)[1] insert.to_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+to", headers=headers).text)[1] insert.without_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+without", headers=headers).text)[1] insert.can_keywords = ujson.loads(requests.get(google_autocomplete_url+var+"+can", headers=headers).text)[1] insert.why_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=why+"+var, headers=headers).text)[1] insert.where_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=where+"+var, headers=headers).text)[1] insert.who_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=who+"+var, headers=headers).text)[1] insert.when_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=when+"+var, headers=headers).text)[1] insert.will_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=will+"+var, headers=headers).text)[1] insert.are_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=are+"+var, headers=headers).text)[1] insert.which_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=which+"+var, headers=headers).text)[1] insert.can_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=can+"+var, headers=headers).text)[1] insert.how_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=how+"+var, headers=headers).text)[1] insert.what_keywords = ujson.loads(requests.get("https://google.com/complete/search?client=chrome&q=what+"+var, headers=headers).text)[1] insert.save() return HttpResponsePermanentRedirect(identifier+'/') This code is making tremendeous network request over 12 seconds. Because of this the page is just loading and loading. As you can see, there are nearly 22 request which are extremely slow. Any help is appreciated. -
Django custom queryset class slicing not working
We are using a custom object(pas1_objects). Once we perform some filter operation we are getting the below query set. all_users_queryset = ( User.pas1_objects.select_related("userlogindetails", "usermeta", "tenant").filter(data_filter) .exclude( userrolepermissions__role_id__in=["PG", "PD"], tenant_id__in=tenant_ids ) .order_by(*sort_array) ) the output of the above query is - <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>, <User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>, <User: User object (4a24f883-210b-43a6-9b57-f51fac624a09)>, <User: User object (b6b044c6-cf9b-46f9-91d9-3a31cd4f6d30)>]> Slicing on this query set is not consistent. (Pdb) all_users_queryset[0:1] # first slice is giving correct output <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[1:2] # this should return 2nd obj in the query set but it return 1st object <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[2:3] # this works fine <KafkaPushQuerySet [<User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>]> (Pdb) all_users_queryset[0:2] # this is returning 1st two objects but in reversed order. <KafkaPushQuerySet [<User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>]> (Pdb) all_users_queryset[0:3] # this is returning correct objets and in correct order. <KafkaPushQuerySet [<User: User object (bbc306a1-3a75-4e5e-a9b4-6dce0b31b4b3)>, <User: User object (8830ecc1-944a-43e3-a701-331122a26c2b)>, <User: User object (25255aa5-31f9-45d4-9158-5225fba24cb3)>]> What can be causing this inconsistency? Thanks!!! -
How do I optimize ORM queries for faster results?
I have 80k+ Entries in table(Model) Calendar. When I run either of the following 2 methods, the filter or get is taking too Long to execute and due to which server is getting crashed after sometime and no new entries are getting added. I want to know if there are any more methods from which I can solve this issue? Method 1: date_list = [] d1 = date(2022, 5, 1) d2 = date(2022, 6, 30) delta = d2 - d1 for i in range(delta.days + 1): date_list.append(d1 + timedelta(days=i)) profiles = Profile.objects.all() for j in date_list: for i in profiles: try: Calendar.objects.get(date=j,emp_id = i.emp_id) except Calendar.DoesNotExist: e = Calander() e.team = i.emp_process e.date = j e.emp_name = i.emp_name e.emp_id = i.emp_id e.emp_desi = i.emp_desi e.att_actual = "Unmarked" e.save() and another method (Method 2): date_list = [] d1 = date(2022, 5, 1) d2 = date(2022, 6, 30) delta = d2 - d1 for i in range(delta.days + 1): date_list.append(d1 + timedelta(days=i)) profiles = Profile.objects.all() for j in date_list: for i in profiles: cal = Calander.objects.filter(date=j,emp_id = i.emp_id).count() if cal < 1: e = Calander() e.team = i.emp_process e.date = j e.emp_name = i.emp_name e.emp_id = i.emp_id e.emp_desi = i.emp_desi e.att_actual = … -
Save a CSV to a model in Django
I am trying to develop a view that saves a CSV fields to a table in a Django model and then save the whole CSVto another table with a fileField. However when I try to save the whole CSV I get: The 'file' attribute has no file associated with it. Why is this? how should I save the CSV to the fileField? models.py: class wordsFile(models.Model): table = models.ForeignKey(WordsTable, on_delete=models.CASCADE) file = models.FileField(upload_to='uploads/%Y/%m/%d/') def save(self, *args, **kwargs): self.file.save(self.file.name, self.file) views.py: def home(request): tp = request.POST.get('tp') elif tp == "Upload CSV": if request.user.is_authenticated: upCSV = request.FILES.get('upload') decoded_file = upCSV.read().decode('utf-8') file = wordsFile().save(decoded_file, save=True) #Here is where I try to save the whole CSV to the fileField of the wordsFile model. io_string = io.StringIO(decoded_file) usr = User.objects.get(username=request.user) for idx,row in enumerate(csv.reader(io_string, delimiter=',')): if idx!=0: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() return redirect("home") -
utilisation des relation many to many et one to many entre 3 models en meme temps
Bonjour, je suis nouveau avec django, je souhaite si possible avoir votre apport sur un sujet qui me bloque. je sais faire des relation one to many et many to many avec Django, seulement je suis particulièrement bloqué pour le coup. j'ai trois table(motif,document,dossier), les table motif et document sont lié par une relation many to many,et les table motif et dossier liés par une relation one ton many. je souhaite que en choisissant un motif dans dossiers, tous les document qui sont lié à lui apparaissent dans dossiers. class Motif(models.Model): m_designation=models.CharField(max_length=50) document=models.ManyToManyField(Document) create_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.m_designation # Create your models here. class Dossier(models.Model): statut=(('Valider en Agance','Valider en Agance'), ('Valider controle BEAC','Valider controle BEAC'), ('Rejeter Controleur BEAC','Rejeter Controleur BEAC') ) devise=(('Euro','EUR'), ('Dollar Americain', 'USD'), ('YEN','JPY'), ('MAD','MAD') ) agence=models.ForeignKey(Agence,null=True,on_delete=models.SET_NULL) raison_sociale=models.CharField(max_length=50) Numero_de_Compte=models.CharField(max_length=50) motif=models.ForeignKey(Motif,null=True,on_delete=models.SET_NULL) devise=models.CharField(max_length=50,choices=devise,default='EUR') cours=models.FloatField(default=650) mt_devise=models.FloatField() beneficiaire=models.CharField(max_length=50) statut=models.CharField(max_length=50,choices=statut,default='Valider en Agance') create_time=models.DateTimeField(auto_now_add=True) def mt_xaf(self,): return int (self.mt_devise * self.cours) # Create your models here. class Document(models.Model): designation=models.CharField(max_length=50) create_time=models.DateTimeField(auto_now_add=True) def __str__(self): return self.designation -
need help in django form ajax implementation, 500 (Internal Server Error)
I'm trying to make a app just like facebook or any social media, the problem starts in my comment section where I implemented ajax. I'm guessing the problem lays in csrfmiddlewaretoken html file script tag here's the view.py Views.py -
How can i filter parents that has at least one active child on parent child relationship model
I have "Category" model which has multiple parent/child relationship. class Category(models.Model): pass class CategoryParent(models.Model): parent_category = models.ForeignKey("Category", related_name="children", on_delete=models.CASCADE) child_category = models.ForeignKey("Category", related_name="parents", on_delete=models.CASCADE) is_active = models.BooleanField(verbose_name=_("Is active?"), default=True) class CategoryExlusion(models.Model): browser = models.ForeignKey("Browser", on_delete=models.CASCADE) country = models.ForeignKey("Country", on_delete=models.CASCADE) category = models.ForeignKey("Category", on_delete=models.CASCADE) I want to list all top-level categories that have at least one active child category. If there is a record on the CategoryExlusion list for a category and the requested user's browser and country, that means this category is not active for this user. I can reach the user's browser and country with request.user.browser and request.user.country. The most difficult issue I'm dealing with is the possibility that my child will have children.