Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When to use an abstract model?
There's a form on our website that gives you a quote if you enter a to and from address. From there, you can go ahead and make a booking or just leave the website. We save the quotes generated by users for statistic purposes (e.g compare the quote and booking ratio). Currently, I use two tables for this. Quotation and Booking. Here are the tables (models in Django): Quotation: to from price some_charge other_charge Booking: to from price some_charge other_charge name # other booking details I have kept them as separate models but I have noticed they are getting very similar over time. I am adding fields to both models and also have duplicate methods. Should I make a QuotationModel and extend both from that? Any other suggestions? Any theory I should for a scenario like this? -
How to filter select options based on dynamic queryset
im having a situation, i need a formset with dynamic select options. lets assume i have 3 models Book -> Chapter -> Comment # ============ models.py ============= class Book(models.Model): name = models.CharField(_("Book name"), max_length=50) class Meta: verbose_name = _("book") verbose_name_plural = _("books") def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(_("Chapter name"), max_length=50) book = models.ForeignKey(Book, verbose_name=_(""), on_delete=models.CASCADE) class Meta: verbose_name = _("chapter") verbose_name_plural = _("chapters") def __str__(self): return self.name class Comment(models.Model): comment = models.TextField(_("Chapter comment")) chapter = models.ForeignKey(Chapter, verbose_name=_("Chapter"), on_delete=models.CASCADE) class Meta: verbose_name = _("Comment") verbose_name_plural = _("Comments") def __str__(self): return self.name # ============ Forms.py ============= class CommentForm(forms.Form): chapter = forms.ModelChoiceField(Chapter.objects.all()) # <~~~~ Here is the problem comment = forms.CharField(max_length=50, required=True) . I have a page url '/book/{id}/comment' , In this url the users will comment on one or more chapter using a formset + jQuery to handle the addrow button . . How can i filter the queryset (of chapter) to match chapters from the book i selected in the id? -
How to render a page with prompt from views in Django?
I'm currently attempting to modify a page that essentially keeps track of when a user enters/leaves an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own "estimate" of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. I'm fairly new to Django/Python. I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off. These is a summarized version of what the models look like: models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) edited_timestamp = models.DateTimeField(null=True, blank=True) time_exceptions = models.CharField(max_length=2, blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) time_out = models.DateTimeField(blank=True, help_text="Time out", null=True) def __str__(self): return self.employee_number I figured that the easiest way to do this is by adding it to the logic in views.py, to prevent updating a wrong record, in such a way that, right after an entry gets flagged, the user is prompted to enter the date/time … -
django get all related record using post_save/pre_save
I just want that when the admin update the student enrollment record (picture1) and get all the related record in ScheduleOfPayment(picture2) and must be added automatically in StudentsPaymentSchedule(picture3) (remarks, date, amount Payment Schedule from ScheduleOfPayment) class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Payment_Schedule = models.DateField(null=True, blank=True) Amount = models.FloatField(null=True, blank=True) Remarks = models.TextField(max_length=500, null=True, blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Payment_Type != instance.Payment_Type or \ older_instance.Education_Levels != instance.Education_Levels: StudentsEnrolledSubject.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None studentspayment = ScheduleOfPayment.objects.filter(Education_Levels=instance.Education_Levels, Payment_Type=instance.Payment_Type) for each in studentspayment: StudentsEnrolledSubject.objects.create( Students_Enrollment_Records=instance, Payment_Schedule=each) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) picture 1 picture 2 picture 3 -
Django fails to serve static file in ec2?
I was trying to deploy a a django project on ec2 instance using nginx and uwsgi. The project works fine in development mode on local pc and can serve static files in localhost easily. But problem is after deploying on ec2 instance it can not load static files(css) files. My project structure: Settings files are inside setting directory: Some part of Settings contents: BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "control", ] STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) nginx contents: upstream url_shortener { server 127.0.0.1:8000; } server { listen 80; server_name mahbubcseju.com ; charset utf-8; location = /favicon.ico {access_log off; log_not_found off; } location = /static/ { autoindex on; alias /home/ubuntu/projects/url_shortener/static/; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass url_shortener; } } uwsgi contents: [uwsgi] project = url_shortener uid = ubuntu base = /home/%(uid) home = %(base)/projects chdir = %(home)/%(project) module = %(project).wsgi:application master = true processes = 5 chown-socket = %(uid):www-data chmod-socket = 666 socket = 127.0.0.1:8000 vacuum = true plugins = python3,http -
How to download document from Bootstrap Modal window?
I have Detail Views where users can download a document by clicking this button: <a class="btn btn-default" href="{{ memo.word_file.url }}"> <span class="fa fa-download"></span> Download </a> This button has now been put in a Bootstrap Modal window so that the user doesn't have to be redirected to a new page to download the document. Issue is that the data such as {{ memo.content }} are showing up in the Modal window but all the buttons do is close the Modal window. Another thing to note is that the glyphicons are not showing up either which has me confused. This is the Modal window: <!-- Modal --> <div aria-hidden="true" aria-labelledby="ModalScrollableLabel" class="modal" id="ModalScrollable{{ memo.id }}" role="dialog" tabindex="-1"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="white-box"> <div class="modal-header"> <h5 class="modal-title" id="ModalCenteredLabel{{ memo.id }}"> {{ memo.title }} </h5> <button aria-label="Close" class="close" data-dismiss="modal" type="button"> <span aria-hidden="true"></span> </button> </div> <div class="modal-body"> {{ memo.sender }} | {{ memo.date_time|date:"M d, y" }} </div> <div class="modal-body"> {{ memo.content }} </div> <div class="modal-footer"> <a class="btn btn-default" href="{{ memo.word_file.url }}">Download</a> <button class="btn btn-default" type="button">Close</button> </div> </div> </div> </div> Thoughts on why this could be? I am not sure if this has to do with something in Django's template tags so I am adding that … -
Change function jquery didnt send value to views.py (didnt work)
so i want to make a 2 dropdown but second dropdown dependent on the value on the first dropdown html code for the select dropdown option <form class="form-horizontal style-form" action="#"> <div class="form-group"> <label class="control-label col-md-3">Database Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id="tableselect" style="width:425px;background-color:white;height:30px;"> <!-- <li><a href="#"></a></li> --> {% for table_name in obj %} <option value="{{table_name.table_name}}">{{ table_name.table_name }} {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id ="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> </form> {% block extrajs %} #all the js script source i put here <script> $(document).ready(function() { $('#tableselect').change(function() { var url = "{% static url 'load-data' %}"; var table_name = $(this).val(); $.ajax({ url : url, data : { 'table_name' = table_name }, success : function(data){ $('#dataselect').html(data); } }); }); }); </script> {% endblock %} views.py where i put the process the request here def load_data(request): table_name = request.GET.get('table_name') dsn_tns = cx_Oracle.makedsn('ip', 'port', sid=' ') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() obj2 = c.execute ('SELECT table_name FROM ALL_TABLES WHERE owner = '+table_name+'') context = { 'obj2' : obj2 } return render(request,data_list.html,context) data_list.html where the … -
Django custom migration RunPython cannot access ForeignKey field in another database
I'm writing a django migration operation to change some data in the 'default' database. My app has access to a 'services' database, which contains data I cannot change. The two relevant fields in the default.table are: data_sets_to_remove = models.CharField(blank=True, null=False, max_length=100, default="") data_sets_new = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True) i.e., i'm migrating data from data_sets_to_remove into a new format and adding to data_sets_new. To do this, I need to access data from the 'services' database in the migration operation. def forwards_func(apps, schema_editor): DataRelease = apps.get_model('registry', "datarelease") Survey = apps.get_model('registry', "survey") data_release_queryset = DataRelease.objects.using('services').all().values('id', 'name', 'survey') But for some reason, the foreign key field 'survey' on the DataRelease model is not available in this context. django.core.exceptions.FieldError: Cannot resolve keyword 'survey' into field. Choices are: id, name Can anyone shed any light on this? I assume the issue is around accessing data from a secondary database within a migration operation, but if i run the same code in the console, it works fine... The relevant Survey and DataRelease models: class Survey(models.Model): name = models.CharField(blank=False, null=False, max_length=100, unique=True) class DataRelease(models.Model): name = models.CharField(blank=False, null=False, max_length=100) survey = models.ForeignKey(Survey, related_name='data_releases', on_delete=models.CASCADE) -
Convert python string "['a', 'b']" to list
I have a form that save lists as strings, I want to convert those strings to lists before save in DB. I'm using python3 and Django. The strings looks like: '["MEX","MTY","GDL","BJX","QRO","PBC","TLC","CUN","EM","CUU"]' what will be the most pythonic way to do that? -
Django post_signal insert and update
I just want that when the admin update the student enrollment record (picture1) and get all the related record in ScheduleOfPayment(picture2) and must be added automatically in StudentsPaymentSchedule(picture3) class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Payment_Schedule = models.DateField(null=True, blank=True) Amount = models.FloatField(null=True, blank=True) Remarks = models.TextField(max_length=500, null=True, blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Payment_Type != instance.Payment_Type or \ older_instance.Education_Levels != instance.Education_Levels: StudentsEnrolledSubject.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None studentspayment = ScheduleOfPayment.objects.filter(Education_Levels=instance.Education_Levels, Payment_Type=instance.Payment_Type) for each in studentspayment: StudentsEnrolledSubject.objects.create( Students_Enrollment_Records=instance, Payment_Schedule=each) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) picture 1 picture 2 picture 3 -
How to fix Django problem "Page not found (404)"
Recently I've started my first project on Django. Then, I created the first project's page called "login". I put the URL: urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login_user) ] created the function on view to render the page: def login_user(request): return render(request,'login.html') and I created the file login.html in a folder inside my application called templates. However, when I ran the server, I started having a problem. Every time I accessed The Django installation page, there was a "page not found (404) problem", and when I went to login's page, it showed that the template does not exist at login.html, even though it does exist. I have already tried to put Debug = false and set the allowed_host = ["*"], and then, when I access the initial page, it says "Not Found. The requested resource was not found on this server", and when I access the page login, it shows a server error (500). I wanted some help on how to solve this problem. -
Wagtail PostgreSQL search backend shows warning "MyModel.search_fields contains non-existent field" yet is fully functional and operates as expected
Hi thanks for your help in advance! On a wagtail 2.2.2 project I recently added search functionality with PostgreSQL search backend. It was working great until I tried running a search on a filtered PageQuerySet by given tag whichs throws this error: FilterFieldError at /blog/tags/tag_slug/ Cannot filter search results with field "tag_id". Please add index.FilterField('tag_id') to BlogPost.search_fields. Django Version: 2.0.13 Python Version: 3.6.8 ... File "/path/to/env/lib/python3.6/site-packages/wagtail/search/queryset.py" in search 12. operator=operator, order_by_relevance=order_by_relevance, partial_match=partial_match) File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in search 371. partial_match=partial_match, File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _search 359. search_query.check() File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in check 157. self._get_filters_from_where_node(self.queryset.query.where, check_only=True) File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _get_filters_from_where_node 108. child_filters = [self._get_filters_from_where_node(child) for child in where_node.children] File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in <listcomp> 108. child_filters = [self._get_filters_from_where_node(child) for child in where_node.children] File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _get_filters_from_where_node 100. return self._process_filter(field_attname, lookup, value, check_only=check_only) File "/path/to/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _process_filter 73. field_name=field_attname Exception Type: FilterFieldError at /trust-worthy/tags/presentation/ Exception Value: Cannot filter search results with field "tag_id". Please add index.FilterField('tag_id') to BlogPost.search_fields. I added the FilterField to the BlogPost model search_fields like it said and it seems to be working fine with correct search results returned on the filtered set. The only problem now is that every time Django boots up it shows this warning: System check identified some issues: WARNINGS: blog.BlogPost: … -
Sort Django models based on the maximum value of multiple fields
I have a model that stores data for teams. Each team has three fields for each match played (match1, match2, etc.) that store a point value. I need to be able to sort these teams based on the highest score in any of the three matches, but Django's order_by method only sorts based on the max of one value. Is there a way for me to provide multiple parameters and have it choose the greatest value when sorting? Here is what my code looks like so far: #models.py class Team(models.Model): match1 = models.CharField(max_length=4, blank=True, default="/") match2 = models.CharField(max_length=4, blank=True, default="/") match3 = models.CharField(max_length=4, blank=True, default="/") #views.py def team_rankings(request): # Scoreboard/rankings of teams context = { 'teams': Team.Objects.all().order_by(#All three match results here) } return render(request, 'scoring_system/rankings.html', context) -
Html - Making the form responsive when changing size of page
In my Django project, I am to make my site fully responsive. So far, I do this by adding this piece of code for my background: CSS: div { background-image: url("{% static 'spotifywallpaper.jpg' %}"); background-size: cover; width: 100%; height: 100%; } I then have a form. I generate this form using Django. Here is my form code in html: {% for field in form %} {{ field }} <br> {% endfor %} CSS: .signupform { position: absolute; background-size: cover; left: 600px; top:150px; } When I resize my page, the form stays static and does not move. What I want is when I shorten my page down in resolution, I want to make the form cover the page so it can then be actually seen by the user. Any ideas on how to accomplish this? Thank you. -
Adding more filters to an URL when using Django Rest Framework
I created a Django Rest Framework API endpoint. This is the view: class myApiList(generics.ListCreateAPIView): queryset = tst.objects.using.all() serializer_class = mySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('Status',) This code lets me add filters when retrieving data from the API endpoint using Jquery on a standard webpage. So, if on my page i want to show only the records with the status Free i will retrieve this endpoint: ("/myApi/?Status=Free") But what if i want to show not only the items with the status Free, but also those with the status Pending? I tried this, but it's not working, as it will only show the records with the status Pending ("/myApi/?Status=Free&Status=Pending") Is there a way to solve this? Should i change something in the URL or do i have to make some changes from my Django Backend? -
Django sorl thumbnail cache image path mismatch when using manage.py dumpdata
I'm trying to migrate data from staging to local copy of my site. The images in the media folder are all transferred okay. Then I use the following command to export my staging site python manage.py dumpdata --exclude contenttypes > db.json I then take the db.json file and load it to my local copy of the django site using the following command. python manage.py loaddata < db.json Some of the images shows up and some don't, after comparing those image tags src between staging and local. I realized that they don't match up. For example, an image is referencing a file here on the staging site /media/cache/a0/83/a083042025374b34c59547e857a4d3fa.jpg becomes this: /media/cache/78/c6/78c6f6982cc063cd9f82939037d990a3.jpg These are generated by Sorl-thumbnail. Anyone knows why?? -
Using Django SQL Explorer how do I correctly set default dates for paramters with PostgreSQL backend?
Our Django application just migrated from MySQL to PostgreSQL, and we are in the process of updating our user queries to use the correct syntax. These queries are stored/executed via Django-SQL-Explorer. I have a query that for simplicity's sake looks like this: SELECT * FROM table t WHERE t.scheduled_start_date BETWEEN $$from_date$$ AND $$to_date$$ The query above works, but I would like to set defaults for today & today+30 respectively. I've tried the following WHERE clauses to no avail: Works with user entered date, default throws syntax error WHERE t.scheduled_start_date BETWEEN date('$$from_date:CURRENT_DATE$$') AND date('$$to_date:CURRENT_DATE + INTERVAL \'30 DAY\'$$') Error using defaults: syntax error at or near "30" LINE 28: ...urrent_date') AND date('current_date + interval \'30 day\'') ^ Defaults work correctly, but user entered dates do not: WHERE t.scheduled_start_date BETWEEN date($$from_date:CURRENT_DATE$$) AND date($$to_date:CURRENT_DATE + INTERVAL '30 DAY'$$) Error with user dates: function date(integer) does not exist LINE 28: WHERE t.scheduled_start_date BETWEEN date(2019-09-30) AND da... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. The message about casting makes sense to me since the user enters in string data, however I can't seem to get the syntax right that casts to DATE but … -
Integration Django and Bokehn - does not display plot
I'm trying to integrate Django and Bokeh using enter link description here Unfortunately after writing the plot function it does not display anything. my views.py def homepage(request): x = [1,2,3,4,5] y = [1,2,3,4,5] plot = figure(title = 'Line Graph', x_axis_label='X-Ax',y_axis_label='Y-Ax',plot_width = 400,plot_height = 400) plot.line(x,y,line_width = 2) script,div = components(plot) return render(request,'repositorys.html',{'script': script,'div': div}) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^repositorys/',views.homepage,name='repositorys'), url(r'^repositorys/(?P<pk>\d+)/$', views.repositorys_board, name='repositorys_board'), url('admin/', admin.site.urls), ] and repositorys.html <html> <head> <link href=”http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.css" rel=”stylesheet” type=”text/css”> <link href=”http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel=”stylesheet” type=”text/css”> <script src=”http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.js"></script> <script src=”http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.js"></script> {{ script | safe }} </head> <body> {{ div | safe }} </body> </html> My bokeh version is 1.4.0 Unfortunately on my localhost nothing is displayed -
How do I put links in spreadsheets to django that don't redirect to the login screen
Apologies, there is probably already responses to this but I can't even isolate where the problem is - Django or Excel I have an Excel spreadsheet that I've created with urls to Django resources e.g. rows that look like http://site/app/object/17234/ I built them as database extract with a string concatenation of id and the rest of the url. (e.g. select 'http://site/app/object/'||obj.id||'/' from ...) As far as I can see in excel they have the right structure and nothing weird. I've already authenticated on the site with 14 day token expiry If I copy and paste them into chrome they work If I create desktop shortcuts using the URLS they work BUT if I click on them within excel they open chrome but go to the login screen http://site/accounts/login/?next=/app/object/17234/ If I log in from there it correctly redirects but this is a step I don't think I should have to do. I am hoping someone can explain where this is happening, why and how to fix it. -
how to implement the idea of dependent model fields in django?
I am creating an app that has Post and Tag as models the post has tags, each tag describing the post somehow, for example a post has the following tags #backend_development #coding and I am relating the Post model to the Tag model by a ManyToManyField and each post creator chooses the tags from a pre-populated list from the database, meaning they don't create the tags on the post, they just choose them. the thing is I am trying to classify those tags somehow, for example , to have all the tech related tags are under a tech field in the list when clicked it displays all the tech related tags, if it's a business field for example it displays all the business related tags how can I implement this classification ? should I build another model called SubjectTag for example to include the subjects of all the tags and relate it with the Tag model? should I not do that and use some kind of html magic that can do this trick for me ? I don't know , what do you think ? -
python fragmented data pandas , DASK
what is the difference of using //DASK b = db.from_sequence(_query,npartitions=2) df = b.to_dataframe() df = df.compute() //PANDAS df = pd.DataFrame(_query) I want to choose the best option to fragment large amounts of data and without losing performance -
How to access request url pk from throttle class?
I am a newbie to Django and I am building a Django application that uses REST API. I have a throttle class and I want to restrict users to send more than 5 number of invitations to the same user in one minute. I send user ID with URL and I should access pk in order to use it for the caching operation. How can I access pk from the throttle class? For example: api/users/3299143165471965406/resend-invitation-email/ Pk will be: 3299143165471965406 views.py @decorators.action(methods=['post'], detail=True, serializer_class=None, permission_classes=[core_permissions.IsCompanyAdmin], url_path='resend-invitation-email', throttle_classes=[throttles.ResendInvitationThrottle]) def resend_invitation_email(self, request, pk=None): user = get_object_or_404(User, pk=pk) if user.invitation_status == User.INVITATION_STATUS_ACCEPTED or user.invitation_status is None: raise ValidationError("This user is already registered.") else: invitations_tasks.send_invitation_email.delay(pk) return response.Response(status=200) throttle: class ResendInvitationThrottle(SimpleRateThrottle): scope = 'invitation' def get_cache_key(self, request, view): invited_user_id = 1 # Here I should use PK return self.cache_format % { 'scope': self.scope, 'ident': invited_user_id } -
django why i can't see image file?
I tried to load img file, but it dosen't work. I upload img file by admin. thanks to help! here is my code in urls.py path('main/archive/<int:video_id>/', views.loadphoto, name='loadphoto'), in views.py def loadphoto(request, video_id): target_img=get_object_or_404(Record, pk=video_id) context={'target_img':target_img.picture} in models.py class Record(models.Model): record_text = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') picture=models.ImageField(blank=True) def __str__(self): return self.record_text in img.html <img src="target_img"> <a href="{%url 'main'%}">Main</a> -
How to correctly "prompt" the user for a value based on logic in views.py in Django?
I'm trying to modify a page that essentially keeps tracks of when users enter/leave an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own "estimate" of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. I'm fairly new to Django/Python, and I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off. These is a summarized version of what the models look like: models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) edited_timestamp = models.DateTimeField(null=True, blank=True) time_exceptions = models.CharField(max_length=2, blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) time_out = models.DateTimeField(blank=True, help_text="Time out", null=True) def __str__(self): return self.employee_number I figured that the easiest way to do this is by adding it to the logic in views.py, to prevent updating a wrong record, in such a way that, right after an entry gets flagged, the user is prompted to enter the date/time they … -
Concurrency issue or something else? .save() method + DB timing
So the situtation is this: I have an endpoint A that creates data and calls .save() on that data (call this functionA) which also sends a post request to an external 3rd party API that will call my endpoint B (call this functionB) def functionA(): newData = Blog(title="new blog") newData.save() # findSavedBlog = Blog.objects.get(title="new blog") # print(findSavedBlog) r = requests.post('www.thirdpartyapi.com/confirm_blog_creation/', some_data) # this post request will trigger the third party to send a post request to endpoint calling functionB return HttpResponse("Result was: " + r.status) def functionB(): blogTitle = request.POST.get('blog_title') # assume this evaluates to 'new blog' # sleep(20) try: findBlog = Blog.objects.get(title=blogTitle) # again this will be the same as Blog.objects.get(title="new blog") except ObjectDoesNotExist as e: print("Blog not found!") If I uncomment the findSavedBlog portion of functionA, it will print the saved blog, but functionB will still fail. If I add in a sleep to function B to wait for the DB to finish writing and then trying to fetch the newly created data, it still fails anyway. Anyone with knowledge of Django's .save() method and/or some concurrency knowledge help me out here? Much appreciated. Thanks!