Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to model tournaments database into a SQL in django
I want to model a tournament database to store data of online games My question is: How to create a model in relationship database to store all this types of tournaments? (such as, league of legends tournament, dota 2 tournament) For example, a tournament can have 8 teams or 5 teams. This is the sketch I created in my mind. What things do you suggest (especially I need help with relationships of tables). Also how to keep team 1 and team 2 in the match table (such as, scores, winner, loser) i thought; Game database game_id,name Player database player_id,name,surname,country,Game(FK).. ( and some other fields) Team database team_id,name,country,game,Player(ManyToMany).. ( and some other fields) Match database match_id,name,match_game,match_map,team1,team2,winner,loser,date,duration,score1,score2.. ( and some other fields) Tournament database tournament_id,tournament_name,tournament_game,Match(ManyToMany).. ( and some other fields) -
How to keep the user logged in to a page react to the Admin page of my api django?
I have an application already running in django, I include in the header of the page a link for the user to access the django admin, how can I do to when clicking the link the admin open with the user's credentials already logged in. Is it possible to do this with react or is it better to do with django? This is the excerpt present on the react page that does the redirect <a href={${API_HOST}/admin} className="dropdown-item children-menu">Admin</a> Currently when I click on the link the redirection occurs correctly however I need to enter username and password againThis is my nav header with link to the Admin page -
django dynamic search bar without refreshing page for a particular field
I am new to django and I want to apply individual search bar for each of my model field using ajax in my centre list. It means I don't want to refresh my page and want to display the search item as I type in the search box. Please help me!! In models.py file class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) In views.py file @method_decorator(login_required(login_url='/'), name='dispatch') class centre(CreateView): fields = ('name','address','contact','phone',) model = Centre success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): form.save() return super(centre, self).form_valid(form) @method_decorator(login_required(login_url='/'), name='dispatch') class CentreListView(ListView): context_object_name = 'centres' model = Centre @method_decorator(login_required(login_url='/'), name='dispatch') class CentreUpdateView(UpdateView): fields = ('address', 'contact', 'phone') # mention the fields to be updated while updating a school model = Centre -
Django urls page not found
In my urls.py I include my urls for each app, for example; from app.insight import urls as insight_urls urlpatterns = [ path('insight/', include(insight_urls), name='insight') ] In insight.urls I include the view and the url like this: urlpatterns = [ path('create/', InsightAddView.as_view(), name='create-insight') ] The error I get says: Page not found. No insight found matching the query However, when I change the create-insight url from create/ to create/new/ it works. Why doesn't the create/ url work? -
How to selectively process parts of a large dataset without reloading the page in Django?
I have an app which allows the user to upload a large datafile, process its contents into a python object (not Django model), and then present a summary of the contents to the user. In other words, the big data is present in the view and summarised to the template. The user then selects which of the content sections to save to the database, and submits the form to do so. I'm wrestling with how to pass the python object to the AJAX-called function without having to do all the processing again? I've used AJAX in the past and have read the answers to suggestions for not reloading pages etc, but none of them have involved passing large objects from within a view. # retrieve the file storage = TemporaryParseStorage.objects.get(id=item_id) # open the file from memory f = open(storage.file.path, "r") file_text = f.read() # Parse the file: parser = Parser() # Process its contents to create the object - I want to store this # object and call its member functions based on a button click in the template objectIWantToKeep = parser.parseModel(file_text) # Builds tree for preview tree = build_tree_from_model(storage, model) context = { 'storage': storage, 'model_name': model.name(), 'tree': tree … -
Django: Count only the latest object for each month
I am building a django based app to collect statistics about the users of a certain software. The goal is to display a chart with the number of users using a version for each month. Here is the model: class Installation(models.Model): userid = models.IntegerField() version = models.CharField(max_length=25) timestamp = models.DateTimeField(auto_now=True) where timestamp is the time when data about the user is collected. Here is how a sample table looks like: | userid | version | timestamp | |------------------------------| | 1 | 3.1 |<sometime> | |------------------------------| | 2 | 3.1 |<sometime> | |------------------------------| | 1 | 3.2 |<sometime> | |------------------------------| | 3 | 3.1 |<sometime> | <sometime> represents different timestamps from the same month. It shows that the userid = 1 upgraded to version 3.2 within the same month. Here is my approach: version_by_month = PortInstallation.objects .annotate(month=TruncMonth('timestamp')) .values('month', 'version') .annotate(Count('userid', distinct=True)) But it has a problem that it will count one user for two versions. For example, it counts userid = 1 for both versions 3.1 and 3.2 and returns the count for users using version = 3.1 as 3, which actually should be 2. For each month I am expecting to have an output in which if a user changes … -
Is there a way to create a Live Dashboard on a .Net web application using Django Python
I have not yet created but want to know if it is possible to somehow embed a dashboard that is created in Django into a .net web application. Is this to show live updates of jobs running for the user. I have not yet created No code as not created -
Django dependent form drop down
I'm creating an online bnb replica site where the user enters/registers his house/property. The idea is that the user enters the relevant data and selects his city from a drop down menu (Karachi, Quetta etc). After selecting the city, the areas of that particular city are to populate the adjacent drop down. (example: If the user selects Quetta then the areas of Quetta such as Satellite town, Model Town etc are to show) I've read through many forms,articles etc but I wasn't able to duplicate it or it's better to say understand it. So far I've just designed the models and views. Please check and give me some ideas on how to achieve it. view.py class halladd(CreateView): model = HallData template_name = "hallfiles/hall.html" form_class = HallForm def get_success_url(self): return reverse('Home-Page') models.py class City(models.Model): city_name = models.CharField("City" max_length = 150) City_CHOICES = [ (Karachi, 'Karachi'), (Lahore, 'Lahore'), (Islamabad, 'Islamabad'), (Quetta, 'Quetta'), ] hall_city = models.CharField("City", max_length = 32, choices = City_CHOICES, default = Quetta) class CityArea(models.Model): city = models.ForeignKey(City) area_name = models.CharField(max_length = 150) class HallData(models.Model): hall_name = models.CharField("Hall Name", max_length=128) hall_city = models.ForeignKey(City) hall_area = models.ForeignKey(Area) urls.py from .views import ( halladd ) urlpatterns = [ url(r'^(?i)halladd/$', halladd.as_view(), name='-View'), ] … -
[ Write API get data ]
I was assigned to write an API. The parameters of this API will be provided to partners. Our partners will submit data to this API. I was suggested by the boss to use Django to create this API. Have you guys ever done this same job? Please let me hear about ideas for making this API. Thank you for reading. I use Python. -
Page is not found while downloading the file in Django
i am working on code for pdf download that same pdf file would be downloaded every time when user click the download but when i click on download i get page not found error. as well as browser showing the path that is not the actual path of that file..my file path is /home/ujjwal/project/media. here is my settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL=' /media/' and urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html file: <a href="/media/bhagwati_invoice.pdf"> <button class="btn" style="width:100%"><i class="fa fa-download"></i> Download</button></a> and getting following error Page not found (404) Request Method: GET Request URL: http://localhost:8000/media/bhagwati_invoice.pdf -
Parallax Not functioning properly : Django
I have downloaded the template : http://keenthemes.com/preview/megakit/ On the index page there is a parallax : <div class="js__parallax-window" style="background: url(img/1920x1080/07.jpg) 50% 0 no-repeat fixed;"> <div class="g-container--sm g-text-center--xs g-padding-y-80--xs g-padding-y-125--sm"> <div class="g-margin-b-80--xs"> <p class="text-uppercase g-font-size-14--xs g-font-weight--700 g-color--white-opacity g-letter-spacing--2 g-margin-b-25--xs">Subscribe</p> <h2 class="g-font-size-32--xs g-font-size-36--md g-color--white">Join Over 1000+ People</h2> </div> <div class="row"> <div class="col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1"> <form class="input-group"> <input type="email" class="form-control s-form-v1__input g-radius--left-50" name="email" placeholder="Enter your email"> <span class="input-group-btn"> <button type="submit" class="s-btn s-btn-icon--md s-btn-icon--white-brd s-btn--white-brd g-radius--right-50"><i class="ti-arrow-right"></i></button> </span> </form> </div> </div> </div> </div> The Parallax image is basically defined with properties in the line : <div class="js__parallax-window" style="background: url(img/1920x1080/07.jpg) 50% 0 no-repeat fixed;"> Now to use the same in django I changed the url of the image to following: <div class="js__parallax-window" style="background: url({% static 'img_events/1920x1080/04.jpg' %}) 50% 0 no-repeat fixed;" > The only problem the parallax is not working properly in this case, the parallax image size should only be 50% but it causes a mismatch in the height and placement of the testimonials and the background image whereas the same code works in the template -
Form did not saving data in to database on submission
I have created a form through which I am trying to submit data into the database but it redirects without submitting data into the database. This can be easily done by using the admin section. forms.py class InvestorsForm(forms.ModelForm): class Meta : model = Investment fields = ['amount', 'rate'] view.py def InvestView(request): if request.method == 'POST': form = InvestorsForm(request.POST, instance=request.user) if form.is_valid(): amount = form.cleaned_data['amount'] rate = form.cleaned_data['rate'] instance = form.save(commit=False) instance.name = request.user print(instance.name) instance.save() return redirect('myinvest') else: form = InvestorsForm(request.POST) args = {'form':form} return render(request, 'investors/form.html', args) models.py class Investor(models.Model): name = models.CharField(max_length=99) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Investment(models.Model): amount = models.FloatField(blank=False) rate = models.FloatField(blank=False) timestamp = models.DateField(default=datetime.now) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) def __str__(self): return str(self.investor) -
How to add ajax to a button that deletes table rows?
I am working on a project in which a delete button deletes the row from table. But the list page gets reloaded everytime I delete an entry. I dont want it to reload. I just want it to remove the entry from list page but I am not good with ajax. Please help me with the code. Thanks in advance. centrelist.html <script> $(document).on('click','#delete',function(){ var a ; a=confirm("Do you really want to delete the user?"); if(a==true){ var url = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') document.location.href = url.replace('1',id); } }); </script> <tbody> {% for c in centres %} <tr> <td>{{ c.name }}</td> <td>{{ c.address }}</td> <td>{{ c.contact }}</td> <td>{{ c.phone }}</td> <td> <a href="{% url 'NewApp:centreupdate' slug=c.slug %} " style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></i></a> <a href="#" style="color:black ;margin_left:8px;" id="delete" name="{{c.id}}" ><span><i class="glyphicon glyphicon-trash"></span></i></a> </td> </tr> {% endfor %} </tbody> views.py def ajax_change_status(request, pk): userpr = UserProfile.objects.get(pk=pk) userpr.pk = pk if(userpr.verified): userpr.verified=False userpr.save() return HttpResponseRedirect(reverse('NewApp:userlist')) else: userpr.verified = True userpr.save() return HttpResponseRedirect(reverse('NewApp:mail', kwargs={'pk':pk})) -
How to set default datefield and overwrite it as well as set default default datetimefield and overwrite it, all in the same models.py
Two of my models have datefield and datetimefield. They exist in the same models.py file and I would like to set them to be default upon adding to the database / into existence. More importantly, I would also like to overwrite these fields for generating models to test them. After some research, I started to use pytz and django.utils timezone. The problem I run into are runtime errors when I try to overwrite them using python's built in datetime (using things like timedelta etc). So I tried converting pytz.utc.localize(), but it complained that the datetime objects I fed it was not naive, but then when I go back to my original version, it still threw the Runtime error. I've found many ways to get over this, mainly using things like date = models.DateField(("Date"), default=datetime.date.today) which requires import datetime, but the problem here is that I also want to use DateTimeField and now just DateField. So I would use date = models.DateField(("Date"), default=date.today), but this requires from datetime import date. The imports conflict and the entire thing is messing with me class SomeTime(models.Model): moment = models.DateTimeField(default=???, editable=True, blank=True) class SomeDay(models.Model): date = models.DateField(default=???, editable=True, blank=True) I would like to go m … -
How to fix 'Forbidden 403' error about doccano
for the doccano,when I login on the Edge,it's normal and I can pass verification,but login on the Chrome , Forbidden (403) CSRF verification failed. Request aborted. I install doccan by docker , and try to add new account or rebulit but no use. -
How do I check if two instances of a Django model are the same across a set of attributes and annotate a queryset accordingly?
My app has a model "OptimizationResult", where I store results from mathmatical optimization. The optimization distributes timeslots over projects. I need to indicate whether the current results is different from a recent result, based on a set of attributes (in particularly not the primary key) The attribute optimization_run is a coutner for different runs Project is a ForeignKey to the project. By overwriting the __hash__ and __eq__ functions on the model I can compare the different instances by OptimizationResults.objects.filter(proj = 1).filter(optimization_run =1) == OptimizationResults.objects.filter(proj = 1).filter(optimization_run = 2) . But as I understand __eq__ and __hash__ are not available on the database. How would I annotate the results accordingly? Something like OptimizationResults.objects.filter(optimization_run = 2).annotate(same_as_before = Case(When(),default=False)) -
nonetype' object has no attribute 'decode' error when i upload the image to database in django
i am new to ionic4/angular4.i need to upload the profile pic to database.i wrote code but i don't know whether it is correct or not and when i am uploading it i am getting the above mentioned error. backend he is using Django and backend is correct only other requests is accepting.sorry for the bad indentation. .ts getPicture() { const options: CameraOptions = { quality: 70, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, allowEdit: false, sourceType: this.camera.PictureSourceType.CAMERA, correctOrientation: true, saveToPhotoAlbum: false }; this.camera.getPicture(options).then( imageData => { // imageData is either a base64 encoded string or a file URI // If it's base64 (DATA_URL): this.image = this.sanitizer.bypassSecurityTrustUrl( "data:Image/*;base64" + imageData ); // this.imageURI = imageData; this.profileService .postInfluencerProfile(this.image, null, null) .subscribe( response => { console.log(response); }, (error: MavinError) => { if (error instanceof NotFoundError) { alert("Not found"); } else { console.log(error); } } ); }, err => { // Handle error } ); } service.ts postInfluencerProfile( profilePic: File, name: string, emailId: string ): Observable<any> { const url = "****************"; const apiKey = "************"; const sessionID = localStorage.getItem("sessionID"); const formdata = new FormData(); formdata.append("file", profilePic); console.log(formdata); const loginContext = { user_agent: "Dalvik/2.1.0 (Linux; U; Android 6.0.1; Nexus Player Build/MMB29T)" }; const postData = { … -
Pytest: Fixtures inherited everywhere implicitly
I'm trying run this test and I have some troubles. First, test at 113 line: when I use decorator at 112 line, response.status_code is 200 OK, and test at 133 line get 200 OK too. But I don't need 200 OK response at 113 line and I remove 112 line. What I got? I got 403 response, it's true. But (!) at 133 line I got 403 response too! Decorator with fixture in 132 line doesn't work.Okay, I'm swap tests by position. Move 133 line up above test at line 112. And what I got? 200 OK and 200 OK too in test_miss_permissions_list. Wtf? What I'm doing wrong? Full code: gist.github This is pytest version 4.6.4, registered plugins: celery-4.2.1 pytest-cov-2.7.1 pytest-django-3.4.8 pytest-forked-1.0.2 pytest-xdist-1.29.0 pytest-xdist-1.29.0 def test_miss_permissions_list(api_client): response = api_client.get(uri) assert response.status_code == status.HTTP_403_FORBIDDEN @pytest.mark.usefixtures("list_permissions") def test_list(api_client): response = api_client.get(uri) assert response.status_code == status.HTTP_200_OK -
Is there a general way to define models for different forms (perhaps using inheritance/some other method)?
Is there a way to have a general template like structure (similar to parent-child classes in python), so that we can define functions and processes without writing down relatively similar code multiple times for the different forms? I am working on a project where we want to efficiently design 10-15 forms for a website that users will fill multiple times. The previous architecture was not made meticulously and so, is very clunky (has a lot of code duplication, etc). These forms do not have the same number/name of fields. As an example, there could be a form "student" and another form "flowers", the point here being that the two forms are unrelated. Both of these forms have different fields, student may have "name", "parent", "job of parent", while flowers may have "scientific name" and "medicinal uses". Let's say all fields in student are related to "name" and all fields in flowers are related to "scientific_name". Is there a way to define a parent model, that defines this general structure, and then inherit both of these tables from there (the field names have to be different)? I couldn't figure out a way to do that. -
Storing logging information from a Celery task in Django database
Let's say I have the following function that I want to execute periodically in Celery: import logging import requests log = logging.getLogger(__name__) def spam(): data = fetch_some_data() log.info(f'Fetched {len(data)} data') stuff = [] for item in data: try: response = requests.get(url + item) response.raise_for_status() except RequestException as exc: log.error(f'Error when requesting {item}: {exc}') continue stuff.append(response.text) for item in stuff: do_something(item) log.info(f'Processed {len(stuff)} items') When the accompanying task is executed: from hello import spam @app.task def run(): spam() I would like to see the result of the task stored along with the logged messages. Flower for example is able to show the task progress and history but I would like to add the logging information as separate fields (e.g. "Info Messages" and "Error Messages"). Similarly, if using django-celery-results, it could show the same information in the Django Admin view. What's the best way to achieve this? -
GeoDjango Querying location__within=poly uses Boundaries instead of Actual Shape
I'm using GeoDjango to find all points within a Polygon but it seems to be using the Boundaries (NMW,NME,SME,SMW) to find points. So it brings back results that are outside of the primary shape. polygon = Polygon((18.3825363358424 -33.97219070578159,...) Order.objects.filter(location__within=polygon) I would like the query to bring points inside the shape and not inside its bounds. i.e if * was my shape; I'm getting points in # that seems to suggest that it's querying on the bounds instead of the actual shape. ************** ************** ******######## ******######## ******######## Please tell if I'm doing some wrong? -
High Availability functionality for Django
I have a Django server on IPAddres1 and running on port 8000, and it is connected to the Postgre Database on port 5432. Django has API which is exposed for API calls from the GUI of some WEB application and of course it has some defined cron jobs (used by scheduler and worker). I have many cron jobs some are being run on every 5 minutes, some one per day etc. My ittention is to create Active-Passive or Active-Active Django High Availability architecture where second Django server on IPAddress2 (and also running on the port 8000 connected to the same database) will take over all functionalities which are used by the first Django server. I am really not sure how to setup this kind of environment so any help will be highly appreiciated. I suppose API calls will be available from the second Django server. But I am not sure how cron jobs should take over all jobs which are configured to be run (I have many jobs which are being run on every 5 minutes). Since I am really not so deep expert for Django I will really appreciate all suggestions how to resolve this or links to documention … -
Delete object from database automatically if one field is TRUE
Automatically delete an object from the database if one attribute of the object is TRUE. I've tried Django Signals, but it didn't help. class Question(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) question = models.TextField(max_length=200) answered = models.BooleanField(default=False) def __str__(self): return self.name If I change the "answered" field to TRUE in Admin Panel, then this object must be automatically deleted from the database. -
Python - data from the scraper does not go to the database - Django
The scraper should scrape every blog post on each page Data from the scraper should go to the Postgresql database, where the following statistics will be counted: The 10 most common words along with their numbers under the address /stats The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / so far I have focused on the first and second task but I have two problems (one results from the other and vice versa) I do not know how to make the data go to the database and thus I do not know how to do "Counter" Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages … -
Django rest_framework_simplejwt token expiring too fast
With Django I've set up authentication with JWT using the rest_framework_simplejwt app. I believe the default timeout for the access token is 1 day, and even after explicitly configuring it to 1 day in settings.py the token doesn't work anymore after ~10 minutes, and the server returns a 401 response. settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } SIMPLE_JWT = { 'TOKEN_LIFETIME': timedelta(days=1), 'TOKEN_REFRESH_LIFETIME': timedelta(days=7), } I was thinking there might be a problem with the time setting in Django, so in settings.py I put a print of datetime.datetime.now(), which strangely is called twice during startapp, with a 2 hour time difference. Still though if the token lifetime is supposed to be 1 day it should be valid so I'm not sure what's the issue. Any ideas on what the problem might be? Thank you so much in advance.