Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attempted relative import beyond top-level package with Python
I have seen several questions related to this error but I think they are different cases. My Django project has 2 applications and a directory structure like this and I'm facing an issue with relative imports I don't understand the logic. Python allows me to import market from file my_app2/signals.py but it returns ValueError: attempted relative import beyond top-level package if I import portfolio from file my_app1/signals.py. What is the reason and how can I found a wordaround? /my_project /my_project /my_app1 /market.py /signals.py # From this file I'd like to import portfolio.py /my_app2 /portfolio.py /signals.py Files content: my_app1/signals.py from ..my_app2 import portfolio # doesn't work my_app2/signals.py from ..my_app1 import market # works -
How do i validate a extended user's field against a secondary (not the default) database in Django?
forms.py: class CustomUserCreationForm(forms.Form): username = forms.CharField() email = forms.EmailField() personalid = forms.IntegerField() password1 = forms.CharField() password2 = forms.CharField() def clean_username(self): username = self.cleaned_data['username'].lower() r = CustomUser.objects.filter(username=username) if r.count(): raise ValidationError("There is a user with that username already!") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = CustomUser.objects.filter(email=email) if r.count(): raise ValidationError("There is already a user with that email!") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match!") return password2 def save(self, commit=True): customuser = CustomUser.objects.create_user( self.cleaned_data['username'], email = self.cleaned_data['email'], password = self.cleaned_data['password1'], personalid = self.cleaned_data['personalid'] ) return customuser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email','personalid') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields settings.py: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'default', 'USER': 'default', 'PASSWORD': 'defaultpassword', 'HOST': '127.0.0.1', 'PORT': '8243' }, 'secondary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'secondary', 'USER': 'secondaryuser', 'PASSWORD': 'secondarypassword', 'HOST': '127.0.0.1', 'PORT': '11371' } I want to validate 'personalid' field against 'secondary', if 'personalid' exists in 'secondary', then the user can be created, else, prompt error message! Any help is well appreciated! Bless -
Django3 using MySQL - Read-and-update in single transaction
The default isolation level does not allow the following code to work; separate processes can read the same value, set the same value, and cause a miscount. def next_id(): with transaction.atomic(): db_counter = Counter.objects.filter(name=name).first() if not db_counter: # Create count if not exists db_counter = Counter.objects.create(name=name, count=0) count = db_counter.count db_counter.count = count + 1 db_counter.save() return count Some things I have looked at: Setting the isolation level to serializable works, but I fear that is too restrictive. The rest of the application is working just fine with repeatable read. The select_for_update might work, but I do not know how to apply it in the case there is no counter, and a record must be added. I have traced through the Django/MySQL code with the debugger: I am not certain transaction.atomic() does anything, I do not see it emit a START TRANSACTION. How do I ask Django to start a transaction? Thank you. -
Getting data from an API and not from Database
Morning, everybody, I'm an apprentice developer, and I have to develop a REST API with django. So far no problem. The trick is that I don't have to work from a database, but from a Python API in which I use functions that return the data I have to serialize. I put this schema here for you to better understand (the one on the right is the one used by my company) schema of API/DB/FRONT relation I have no problem to get datas and return them on endpoint, my problem is when I want to PUT, DELETE request. My DELETE request works with Postman, but when I trigger it from my forehead in sight, I get a 301 redirection error... For the other requests, I don't see how I can get the data from my form in my Vue Frontend and then pass it as an argument to the python function in Django which must insert it in the db ... Thanks in advance for your help Pixi -
Dose not appear to have any pattern in it
File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
ValueError: Field 'id' expected a number but got 'host'
Django returns me ValueError during migration. It expects ID. I'm new to Django btw. and it's my 3rd project. In others there is not such a problem with User Foreignkey. Can someone help me ? from django.db import models from django.contrib.auth.models import User class Room(models.Model): hosted = models.ForeignKey(User, on_delete=models.CASCADE, related_name="hosted_by") name = models.CharField(max_length=50, ) is_played = models.BooleanField(default = False) max_players = models.IntegerField(default = 4,) players_online = models.IntegerField(default = 1) players_ready = models.IntegerField(default=0) def __str__(self): return self.name -
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