Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form validation vs DRF serializer validation
I'm new to APIs creation in django. I checked DRF serializers and I found them useful when manipulating models in DB. My APIs don't use models they are based on forms. So my question is : what can I get more from using DRF validators then using django forms validators in my views ? maybe the content type is more convenient (application/x-www-form-urlencoded vs application/json) ? -
How can I access a Django models
I've three Django models ModelA, ModelB and ModelC. In my logic either an instance of ModelB or ModelC is associated with ModelA via a OneToOne relationship. I'd like to access the field of_interest via ModelAs backwards relationship to ModelB or ModelC. Is this possible? class ModelA(models.Model): ... class ModelB(models.Model): model_a = models.OneToOne( ModelA, related_name='%(class)s_model_a', of_interest=..., ... ) class ModelC(models.Model): model_a = models.OneToOne( ModelC, related_name='%(class)s_model_a', of_interest=..., ... ) -
Why isn't my for loop executing three times?
I expect three columns but the output gives only one column.It seems like the for loop is executing only once. This is my HTML code ''' <div class="row"> {% for head in heads %} <div class="col-lg-4"> <div class="single-bottom mb-35"> <div class="trend-bottom-img mb-30"> {% if head.latest %} <strong>Latest</strong> {% endif %} <img src="{{baseURL}}/{{head.img}}" alt=""> </div> <div class="trend-bottom-cap"> <span class="color1">{{head.head}}</span> <h4><a href="details.html">{{head.summ}}</a></h4> </div> </div> </div> {% endfor %} </div>''' This is views.py I have introduces three objects. ''' head2=News() head2.head='Coronavirus Updat' head2.summ='Deaths cross 2Lac World Wide' head2.img='2.png' head2.latest=True head2.id=False head3=News() head3.head='Coronavirus Updates' head3.summ='Deaths cross 2Lac World Wide' head3.img='2.png' head3.latest=True head3.id=False head4=News() head4.head='Coronavirus Updates' head4.summ='Deaths cross 2Lac World Wide' head4.img='3.png' head4.latest=False head4.id=False heads={head2,head3,head4} return render(request,"index.html",{'head1':head1,'heads':heads})''' The output prints only one column. I expect Three of them. -
Creation of slots at regular intervals
I need to create time-slots according to a number of songs. For example, s if my playlist has 5 songs then we create the time-interval of slots by the logic, 60/5 = 12 minutes in this example as the number of songs was 5 here. I also provide the start_time and end_time. Here if I provide start_time = 5:00 am and end_time = 6:00 am, total songs = 5 S1: 5:00 - 5:12 S2: 5:12 - 5:24 S3: 5:24 - 5:36 S4: 5:36 - 5:48 S5: 5:48 - 6:00 The Model consists of these three fields: class SlotCreate(models.Model): from_time = models.TimeField(max_length=255, blank=True, null=True) to_time = models.TimeField(max_length=255, blank=True, null=True) songs = models.ManyToManyField('Song') labelling = models.ForeignKey('Labelling',blank=True, null=True) I am checking whether the slot exists with the following query: SlotCreate.objects.filter(from_time=from_time,to_time=to_time,labelling=label).exists(): errors.append("The Slot already exists "+"\n") The problem here is if the user provides: Start_time = 5:00 End_time = 6:00 Total songs = 3 Then the slots already exist in the time interval given above as S1, S2, S3, S4, S5 are already there. The piece of code with which I check above fails to determine this case as S1: 5:00 - 5:20 S1: 5:20 - 5:40 S1: 5:40 - 6:00 Can anyone help … -
how to use name in filtered list to find their origin from model `Item`
class Item(): name=models.CharField(max_length=200) origin=models.CharField(max_length=200) class Condition1(): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=2,max_digits=1000) weight=models.DecimalField(decimal_places=2,max_digits=1000) a=Condition1.objects.filter(size__gt=20, weight__lt=10) when i print a as <table>{% for item in a%} <tr><td>{{ item.name}}</td></tr>{% endfor %}</table> it gives list as Item1, Item10, Item13 in table. so now i want to print their origin and i wrote: origin=Item.objects.filter(name__in=a) however it does not give me anything. I want to use name in filtered list a to find their origin from model Item. How to make it work. What i am missing? -
Django model: fetch last ForeignKey in one query
In Django models, I have two database models like: A(models.Model): .... b = models.ForeignKey(B, related_name='my_a') B(models.Model): .... Now, I would like to fetch all B, but have last A be fetched with the same query. so something like: B.objects.all().annotate(myA=fetch last A) I know for prefetch_related but it is too slow. how can I do it? -
How to feature toggle URLs dynamically in Django rest framework
I am working on a project where we use feature toggles to hide features until they are ready to be released. The pattern we have followed is to simply not route certain endpoints if the feature toggle is off. I.e in urls.py, we only include URLs in the urlconf if the toggle is on. But this means feature toggles only have an effect if the server is restarted. We'd like to be able to dynamically turn feature toggles on and off on a running server. It seems that the urlconf is only parsed at startup time so changes to it are not reflected without a reboot. I've tried making a middleware to block certain URLs based on the value of a feature toggle and that works but doesn't play nicely with the Swagger docs, which I also would like to reflect the state of the feature toggles. In general, it feels like I am fighting the system, which is usually a sign that I'm not approaching it from the right angle. So, how do people advise me to implement dynamic feature toggles of behaviour in Django? -
python django Failed to load my python function code
OS: Linux Debian (last build) Python: 3.7.7 64bit Django: 3.0 Apache2: 2.4.x I'm trying to run and test my Django project on Linux apache2 (Production-Environment ). I want to insert a record in DB via pymysql module (when the entered string by user is correct/incorrect (log)). Below function (check_usr()) works fine in Test-Environment (127.0.0.1:8000). But doesn't work in Production. I'm just seeing content of else section in validation() view via web browser. def check_usr (usernameee): result = subprocess.run(['........'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) result = result.stdout.decode('utf-8') if "successfully" in result: return "ok" elif "activation failed" in result: return "no" else: return "problem" @require_http_methods(["GET"]) def validation(request): usernameee = request.GET["usernameee"] result = check_usr(usernameee) db_connection("init") if result == "ok": args = (ap_ssid, ap_mac, "ok") db_connection("INSERT INTO splash_tble (ap_ssid, ap_bssid, ap_state) VALUES (%s, %s, %s)", args) return render(request, "router/validation.html", {"validation_state": "success"}) elif result == "no": args = (ap_ssid, ap_mac, "no") db_connection("INSERT INTO splash_tble (ap_ssid, ap_bssid, ap_state) VALUES (%s, %s, %s)", args) return render(request, "router/validation.html", {"validation_state": "failed"}) else: return render(request, "router/validation.html", {"validation_state": "problem"}) My config in /etc/apache2/sites-available/routers.conf: DocumentRoot /root/PycharmProjects/router WSGIScriptAlias / /root/PycharmProjects/router/captives/wsgi.py WSGIPythonPath /root/PycharmProjects/router <Directory /root/PycharmProjects/router> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> Alias /static/ /root/PycharmProjects/router/captive_splash/static/ <Directory /root/PycharmProjects/router/captive_splash/static> Order deny,allow Allow from … -
Django - issue displaying context
I would like in my user_profile.html template to filter only the jobs offers related to the category.1, instead here it doesn't display anything. I can't understand if the error is on my models or template. So, in the template it will be something like " if the user score is > 1, then display all the jobs offers that are related to that quiz". If you take the Data Science quiz, you should see only the Data science category offers. Hope I described the issue clearly. I've been working on the issue for days and still can't solve it. core/user_profile.html {% extends 'base.html'%} {% block content %} {% for category,score in categories_scores %} <div class="card"> <div class="card-header"> {{ category.1 }} Score </div> <div class="card-body"> <h5 class="card-title">CONGRATS!</h5> <p class="card-text"> Here your SCORE: </p> <a href="#" class="btn btn-primary">{{ score }}</a> {% if score > 1 %} {% if request.user == user %} <br> <br> <div class="progress"> <div class="progress-bar bg-success" role="progressbar" style="width: 99%" aria-valuenow="99" aria-valuemin="0" aria-valuemax="100"></div> </div> <p class="card-text"> Congratulations! Now you can apply to:</p> <br> {% for job in jobs %} {% if category.1 == job.categoria %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" … -
Django class variable not getting destroyed after response
I have a simple view and I am not getting what's wrong with the logic. I understand lists are mutable, but this it is returning the same object on every response. class IndexView(TemplateView): data = [] def get(self, request, *args, **kwargs): self.data.append(1) return HttpResponse((self.data, f" {id(self.data)}")) When ever I am refreshing the page, I am getting old values in list and same id of object. Output: First time page renders: [1] 139988074103112 Second time page renders: [1, 1] 139988074103112 Third time page renders: [1, 1, 1] 139988074103112 I am not able to figure out why it is happening. Please help me guys. -
Implement ChatFuel in Django
I'm working on a website that sells adventures. After the user purchases an adventure, he receives a link (or a token if necessary) that they can use to start the ChatFuel adventure. Do you have any idea on how to implement that? I'm using stripe for purchases and on the website.com/charge (it confirms that the purchase was successful) I want to show them a link as well -
No Reverse Match Jquery Ajax Call Django
I am working on this like button with javascript and ajax and am getting this no reverse match error when calling it through ajax, but without ajax call everything is working fine. Another thing, this works well in the detail page but not in the homepage and that is where this error pops up. This is the error: Reverse for 'like_post' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[^/]+)/like/$'] js $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "posts:like_post" %}', data: {'slug': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, datatype: 'json', success: function(response){ $('#like-snip').html(response['form']) console.log($('#like-snip').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); views.py @login_required def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) # post = get_object_or_404(Post, id=request.POST.get('id')) # url_ = post.get_absolute_url() is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) urls path('<slug>/like/', views.like_post, name='like_post'), like_snippet.html <form action="{% url 'posts:like_post' post.slug %}" method="post">{% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_slug" value="{{ post.slug }}" class="btn-sm btn-outline-danger">{{ post.likes.count}} Unlike{{ post.likes.count|pluralize }}</button> {% else %} <button type="submit" … -
How can save the data into database in python django which in list form and list is collection of dictionaries?
Hello everyone I am beginner in python django framework and I am stucked in the program please help me. Thanks in Advance. Problem: I am fetching data using requests method and containing every data in dict form and then append it to the list. Now i want to save all the data of the dict into the database as per my models but here I am unable to do that please help me. here is my models code class Question(models.Model): question_title = models.CharField(max_length=300) question_tag = models.CharField(max_length=250) question_url = models.URLField(max_length=300) question_view_count = models.CharField(max_length=50, null=True, blank=True) question_answer_count = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.question_title Here is my views.py file to search the question and save it to database In views.py i am storing data in list which is coming in dict form so basically data is in dict form so how can i perform a loop by which data save into database according to my models.py from the dict form. def questionSearch(request): if request.method == 'GET': question_title = request.GET.get('title',) question_tag = request.GET.get('tag',) url = 'https://api.stackexchange.com/' + f'2.2/search/advanced? order=desc&sort=activity&q={question_title}&accepted=False&answers=1&tagged= {question_tag}&site=stackoverflow' resp = requests.get(url) resp = resp.json() questions = [] question_data = {} for i in resp["items"]: if i["is_answered"]: question_data = { 'question_url': … -
Django: the detail page is not showing(template error)
am working on a Django project where showing the details of post and amount here is my models.py of post class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:my_job", kwargs={"pk": self.pk}) this is my second models which I inherit Loader post class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE, null=True, default='') user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) def get_absolute_url(self): return reverse("Driver:Driverview") def __str__(self): return self.driver_price this is the view.py of both list and details view class offer_view(ListView, SelectRelatedMixin): context_object_name = 'offern' model = Loader_post template_name = "offer.html" def get_queryset(self): qs = Loader_post.objects.filter(user=self.request.user) return qs class offer_view_detail(DetailView): context_object_name = 'offernew' model = Loader_post template_name = "offer_detail.html" here is my HTML page of list view ...when someone clicks on it it shows the detail of next post offer.html {% for my in offern %} <a href="{{my.id}}/">{{my.sender_name}}</a> {% endfor %} and when someone clicks on its route to the detail page .. but it shows template doesn't exist this is my detail page ie. offer_details.hml <p>{{offernew.sender_name}}</p> <p>{{offernew.receiver_name}}</p> {% … -
How can I implement this many to many relationship to self in Django?
I have a repair GUIDE model which has an attributes that takes 'Prerequisites' which can be other guides, so I need to implement a many to many model where each 'Guide' can have many 'Guides' as prerequisites also those guide in prerequites may have their own prerequisites and also one particular guide may be prerequisite guide to more than one guides. Something like in this image.A picture depicting the relationship -
How to query data from mongoDB in Python view when format of data is not a valid filter?
When a user enters a JIRA number from the UI, I get Crucible links that are in the format of - ['https://crucible05.cerner.com/viewer/cru/CCS-28483', 'https://crucible05.cerner.com/viewer/cru/CCS-28520'] In my database, I have crucible links that are present in the format of - ['https://crucible05.cerner.com/viewer/cru/CCS-26041#CFR-2549576', 'https://crucible05.cerner.com/viewer/cru/CCS-26092#CFR-2553342'] (Note the part with the hash which is not present in the data I get above) I need to match all the crucible links that I get from my UI with the ones that are present in the db. I am able to do this matching of links by comparing with substrings using this piece of code - if [e for e in links if e in '\n'.join(crucible_db)]: matching = [e for e in links if e in '\n'.join(crucible_db)] print(matching) Where, links - List of crucible links that I got from the UI crucible_db - List of all the crucible links present in the db If it helps, my Python model looks like this - class reviewComments(models.Model): reviewID = models.CharField(max_length=20, blank=True) commentID = models.CharField(max_length=20, primary_key=True) solution = models.CharField(max_length=50) comment = models.TextField() dateCreated = models.DateField() type = models.CharField(max_length=20, blank=True) crucibleLink = models.URLField(blank=True) authorID = models.CharField(max_length=20) reviewerID = models.CharField(max_length=20) def __str__(self): # pragma: no cover return self.commentID I retrieved all the crucible … -
Django CMS: Aldryn News & Blog Issue
TypeError at /en/ from_db_value() missing 1 required positional argument: 'context' Request Method: GET Request URL: http://127.0.0.1:8000/en/ Django Version: 3.0.5 Exception Type: TypeError -
ValueError: Cannot assign <QuerySet [<Driver: Test Driver>, <Driver: Another Driver>, <Driver: Third Driver>]>
I have a DRF API that is supposed to feed a frontend Android and IOS app. The API has three types of users namely: Driver, Client and Admin. The client is supposed to create a booking record and get assigned a driver automatically by the API. Based on availability days and times. At the moment every day (Sun, Mon, Tue, Wed, Thu, Fri) is a working day and working hours range from 7:00 am to 9:00 pm with working hours inclusive of transition being an hour. For example, booking of 9:00am will take an hour, hence finishing time will be 10:00am, all factors inclusive. Many drivers can have work at the same time. The app should give feedback to the user if they try booking already picked slots. My problem at this time is to loop through already existing drivers from drivers table, left join them to the booking table and and assign them one by one. I was able to assign one driver a job. But when I added drivers, it became difficult. There is something I am not getting well and I do not know what it is. Here are my models. """ models.py """ from django.urls import … -
Django, console shows double GET for a single page request
I'm developing a django server and every time i request a page it appears two GETs for the same page request. The problem isn't from the code because i sent my project to a couple of friends and they run it without any problem and without the double GET's. Even other projects that are not mine and they shouldn't have any kind of problems it happens the same thing when i am the one to run it. I tried to reinstall django and python but it remains the same. Anyone have any idea what can it be? This is what happens when I enter a blank page with the minimum possible code -
Django ( 3.0.3 ) images inserted in my html projects
I’m working with Django and I have problems with images inserted in my html projects I follow many suggestions but nothing works In html I use: {% load static %} body{background: url("{% static 'images/barcelona_1.jpg' %}"); font-family: arial;} <img src="{% static 'images/GreenStart.png' %}" height="130" width="400" alt=""> In urls.py I add: from django.conf import settings from django.conf.urls.static import static urlpatterns = […. ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In settings.py I add: STATIC_DIR = os.path.join(BASE_DIR, 'static/') STATIC = os.path.join(BASE_DIR, 'static/') STATICFILE_DIRS = [ STATIC_DIR, ] -
Get location from firebase database and show on django web server map
Hi Experts i need your helpIn my project i develop a mobile tracking system, Project based on android app and Django web server, So UntilBy using android application i'm able to send continuously location coordinates to Firebase database but problem is...I wan't my Django web server to get location coordinates contiuesly from firebase database and show on Map and move map marker every time when location change, and i don't have any idea how i do this. please tell me how to i achive my task, and if by using firebase database it's not possible then obviously there is an another way. Many Thanks -
How to do form validation with Django?
This is a simple form that is present in my template(comment.html). <form id="my_form" action="{% url 'a' pk=id %}" method="POST"> {% csrf_token %} <input id="in" required minlength="5" name="message" type="text"><br> <button id="click" title="add your comment" type="submit">Comment</button> </form> As you can see there is an input tag inside form whose name is "message".My problem is that when user get this page on his/her computer as a response means they can simply see this form code on their browser. Let assume a user changed the value of the name attribute of input tag and submit the form then I don't get the value of 'message'. Can you tell me how i can write a view to validate my form on the server-side? So that my website stays safe from a malicious user and from a hacker? -
Django URL is not working on anchor tag via ajax call
i'm working on Python Django and i created a view which write and download the csv file. Now i done with Type, URL and data in ajax call and also pass the javascript function in anchor tag. Now issues occur, When i click on button, all data showig on alert, which i want to export in csv but there is no csv download. The download URL is generating in console. when i copy paste this URL in browser and hit enter, so it download the csv file and all data export successfully which i was actually want. The main issue between anchor tag and ajax call in javascript function. Any Dev can resolve my issue? views.py class ServeCSV(ViewBase): TEMPLATE_NAME = None ACTION_ID = None def get(self, request, *args, **kwargs): all_ids = request.GET['id'] all_ids = json.loads(all_ids) data = models.TimeSheet.objects.filter(id__in=all_ids) print(data) ''' print(type(request.GET['id'])) data = query_cache.model_get_or_404(models.TimeSheet, qobj=Q(id__in=ids)) t_id = int(kwargs.get('id')) data = query_cache.model_get_or_404(models.TimeSheet, qobj=Q(id=t_id)) #progress = query_cache.progress_for_student(provider) #data = models.TimeSheet.objects.all() ''' response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition' ] = 'attachment; filename="timesheet.csv"' writer = csv.writer(response) writer.writerow(['TimeSheet info']) writer.writerow( [ 'Activity', 'Client Initials', 'Date', 'Start Time', 'End Time', 'Hours', 'Reviewed', 'Description', ] ) writer.writerow([]) for rows in data: writer.writerow( [ rows.activity.name, rows.client_initials, rows.date_display, rows.start_display, rows.end_display, … -
Run command conditionally while deploying with amazon ECS
I am having a django app deployed on ECS. I need to run fixtures, a management command needed to be run inside the container on my first deployment. I want to have access to run fixtures conditionally, not fixed for first deployment only. One way I was thinking is to maintain a variable in my env, and to run fixtures in entrypoint.sh accordingly. Is this a good way to go about it? Also, what are some other standard ways to do the same. Let me know if I have missed some details you might need to understand my problem. -
How to filter Django ArrayField using lookup
The data present in the ArrayField like below { "submit_candidate" : [ { "requirement" : [ { "name_id" : 14 } ], "candidate" : [ { "name_id" : 2, "rate" : null, "rate_types" : null, "types" : null, "availability" : null, "address" : [ ], "benfit" : false } ] } ], } My Model class SubmittedCandidateInfo(models.Model): requirement = models.ArrayField(model_container=RequirementInfo) candidate = models.ArrayField(model_container=CandidataInfo) def __str__(self): return str(self.requirement[0]) class SubmittedCandidate(models.Model): submit_candidate = models.ArrayField(model_container=SubmittedCandidateInfo) def __str__(self): return str(self.submitted_candidate_id) class Meta: verbose_name_plural = "submitted_candidates" db_table = "submitted_candidate" I'm using this below query to get job_id. SubmittedCandidate.objects.filter(submit_candidate__0__requirement__0__name__job_id=14) But its throwing me error django.core.exceptions.FieldError: Unsupported lookup '0' for ArrayField or join on the field not permitted.