Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO navigation bar problems
i have a problem in navbar when i add links i cant get to the page its keep loading here is the index.html <div id="navbar" class="navbar-collapse collapse"> <ul id="top-menu" class="nav navbar-nav main-nav menu-scroll"> <li class="{% if nbar == 'home' %}active{% endif %}"><a href="{% url 'translation:index' %}">Home</a></li> <li><a href="#service">SERVICE</a></li> <li><a href="#team">TEAM</a></li> <li><a href="#contact">CONTACT</a></li> </ul> </div> urls.py app_name = 'translation' urlpatterns = [ path('', views.index,name='index'), path('start-now/', views.play_video,name='startnow'), ] views.py def index(request): return render(request,'translation/index.html', {'nbar': 'home'}) and when i leave href empty i can get to the page <div id="navbar" class="navbar-collapse collapse"> <ul id="top-menu" class="nav navbar-nav main-nav menu-scroll"> <li class="{% if nbar == 'home' %}active{% endif %}"><a href="">Home</a></li> <li><a href="#service">SERVICE</a></li> <li><a href="#team">TEAM</a></li> <li><a href="#contact">CONTACT</a></li> </ul> </div> -
how to filter by a context object if exists django class based view
can i check if a date selected from the form then filter by dates if not display the other filter , in class based view class MyModel(models.Model): date = models.DateTimeField(auto_add_now=True) #other fields class MyListView(LoginRequiredMixin,ListView): model = MyModel template_name = 'customer_accessory/accessory_customers.html' context_object_name = 'lists' def get_queryset(self): return MyModel.objects.all().order_by('-pk') def get_context_data(self,*args,**kwargs): context = super().get_context_data(*args,**kwargs) context['start_time'] = self.request.GET.get('start') context['end_time'] = self.request.GET.get('end') if start_time and end_time: context['other_lists'] = MyModel.objects.filter(date__range=(start_time,end_time), other filter) context['new_lists'] = MyModel.objects.filter(date__range=(start_time,end_time) ,other filter) else: context['other_lists'] = MyModel.objects.filter(other filter) context['new_lists'] = MyModel.objects.filter(other filter) template <form method="GET"> <input type="text" name="start" id="datepicker1" class="form-control"> to <input type="text" name="end" id="datepicker2" class="form-control"> <button type="submit">search</button> </form> but the error say name 'start_time' is not defined thanks -
Can you store a constant global object in Django?
I am working on a small webpage that uses geospacial data. I did my initial analysis in Python using GeoPandas and Shapely and I am attempting to build a webpage from this. The problem is, when using Django, I can't seem to find a way to keep the shape file stored as a constant object. Each time a request is made to do operations on the shapefile, I need to load the data from source. This takes something like 6 seconds while a standard dataframe deep copy df.copy() would take fractions of a second. Is there a way I can store a dataframe in Django that can be accessed and deep copied by the views without re-reading the shapefile? -
How to start remote celery workers from django
I'm trying to use django in combination with celery. Therefore I came across autodiscover_tasks() and I'm not fully sure on how to use them. The celery workers get tasks added by other applications (in this case a node backend). So far I used this to start the worker: celery worker -Q extraction --hostname=extraction_worker which works fine. Now I'm not sure what the general idea of the django-celery integration is. Should workers still be started from external (e.g. with the command above), or should they be managed and started from the django application? My celery.py looks like: # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) then I have 2 apps containing a tasks.py file with: @shared_task def extraction(total): return 'Task executed' how can I now register django to register the worker for those tasks? -
JSON response returns {"detail":"Not found."}, 404 status code
I'm experiencing a discrepancy between status codes when checking Postman vs. Localhost. The following TestCase passes where response.status_code == 200. Postman returns a 200 as well. However when I make the PUT request when using Localhost I get a 404 status code. When I check the response in developer tools I get {"detail": "Not Found"}. I'm looking to understand what is causing the 404? tests.py class TestUpdateUserPreferences(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user("Tester") cls.credentials = b64encode(b"Mock:secret").decode("ascii") UserPref.objects.create( gender=["MALE"], size=["MEDIUM", "LARGE"], age=["BABY", "ADULT"], user=cls.user ) cls.updated_pref_data = json.dumps({ "gender": ["FEMALE"], "size": ["SMALL"], "age": ["BABY"] }) cls.factory = APIRequestFactory() def test_update_user_preferences_success(self): request = self.factory.put( reverse("user-pref-settings"), data=self.updated_pref_data, content_type="application/json" ) force_authenticate(request, self.user) response = SetUserPrefView.as_view()(request) self.assertEqual(response.status_code, 200) views.py class SetUserPrefView( GenericAPIView, RetrieveModelMixin, UpdateModelMixin): queryset = UserPref.objects.all() serializer_class = UserPreferenceSerializer def get_object(self): user = self.request.user return get_object_or_404(self.get_queryset(), user=user) def get(self, *args, **kwargs): return self.retrieve(self.request, *args, **kwargs) def put(self, *args, **kwargs): return self.update(self.request, *args, **kwargs) def perform_update(self, serializer): return serializer.save(user=self.request.user) serializers.py class UserPreferenceSerializer(serializers.Serializer): gender = serializers.MultipleChoiceField(choices=USER_PREF_DOG_GENDER) size = serializers.MultipleChoiceField(choices=USER_PREF_DOG_SIZE) age = serializers.MultipleChoiceField(choices=USER_PREF_DOG_AGE) def update(self, instance, validated_data): instance.gender = validated_data.get('gender') instance.size = validated_data.get('size') instance.age = validated_data.get('age') instance.user = instance.user instance.save() return instance serializers.py class UserPreferenceSerializer(serializers.Serializer): gender = serializers.MultipleChoiceField(choices=USER_PREF_DOG_GENDER) size = serializers.MultipleChoiceField(choices=USER_PREF_DOG_SIZE) age = serializers.MultipleChoiceField(choices=USER_PREF_DOG_AGE) def update(self, instance, … -
Django inline formset will always create new object instead of update them
I've 2 model First and Second with a FK from Second to First. I created a form for the 2 class and a inline formset for Second. On template I manually designed my form and with jQuery I'm able to add dynamic forms of Second. On UpdateView the form is correctly populated, but when I submit the form, all Second instances are created again with new ids instead of updating them. I double checked that on HTML there are name=PREFIX-FORM_COUNT-id with correct ids, but seems that Django ignores it. I'm using Django 2.2.12 & Python 3.6 Here what I made: models.py class First(models.Model): name = models.CharField(max_length=100, null=False) class Second(models.Model): first= models.ForeignKey(First, null=False, on_delete=models.CASCADE) number= models.FloatField(null=False, default=0) form.py class FirstForm(forms.ModelForm): class Meta: model = First fields = "__all__" class SecondForm(forms.ModelForm): class Meta: model = Second fields = "__all__" SecondsFormset = inlineformset_factory(First, Second, SecondForm) view.py class FirstUpdateView(UpdateView): template_name = "first.html" model = First form_class = FirstForm context_object_name = "first_obj" def get_success_url(self): return reverse(...) def forms_valid(self, first, seconds): try: first.save() seconds.save() messages.success(self.request, "OK!") except DatabaseError as err: print(err) messages.error(self.request, "Ooops!") return HttpResponseRedirect(self.get_success_url()) def post(self, request, *args, **kwargs): first_form = FirstForm(request.POST, instance=self.get_object()) second_forms = SecondsFormset(request.POST, instance=self.get_object(), prefix="second") if first_form .is_valid() and second_forms.is_valid(): return self.forms_valid(first_form … -
Django: 'UtilisateurUpdateView' object has no attribute 'object'
I develop a Django project with inlineformset nested using FormView. I first develop my form using CreateView/UpdateView and it works but when I use FormView I got an error 'UtilisateurUpdateView' object has no attribute 'object' Why I can get access 'object' when I use UpdateView but not with FormView ? I have read that it could come from override method but here doesn't seems to be the case ? forms.py NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, #Utilisateur, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, ) class UtilisateurProjetUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs) PROJETS = Projet.objects.all() UTILISATEURS = Utilisateur.objects.all() self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet'])) self.fields["uti_ide"] = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select, initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur'])) class Meta: model = UtilisateurProjet fields = ('pro_ide','uti_ide',) views.py class UtilisateurUpdateView(FormView): template_name = 'project/utilisateurprojet_form.html' form_class = UtilisateurProjetUpdateForm def get_form_kwargs(self): kwargs = super(UtilisateurUpdateView, self).get_form_kwargs() kwargs['request'] = dict(utilisateur = self.kwargs['pk'], projet = self.kwargs['projet']) return kwargs def get_context_data(self, **kwargs): data = super(UtilisateurUpdateView,self).get_context_data(**kwargs) if self.request.POST: data["utilisateur"] = self.request.user.username data["user_profil"] = self.request.session.get('user_profil') data["application"] = ApplicationFormset(self.request.POST, instance=self.object) else: data["application"] = ApplicationFormset(instance=self.get_object()) return data … -
convert html to text format while extract the table attribute in django RichtextField while extracting the csv
modes.py class Demo(models.Model) risk_description = models.TextField(null=True, blank=True) views.py RiskAssessment.objects.all().values_list('risk_description' , flat=True) o/p i am geeting ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test3', 'test'] ''''test'''' but desired output sholud be removed html tag tag from list -
Update current_week from template in Django
I've build a planning tool to plan activities with standard durations. The total amount of durations is summed up per week and extracted from a weekly planning target. The weekly planning target is based on a contract with weekly hours (see model.py). At the moment I show all plannings of the current week in a table in my template and calculate the remainder (planning target - planned) based on the current week. I want the user to be able to switch to previous and future weeks and I want to let the planned and calculated remainder to switch with it. I've tried to do this via a form (don't know how to build the right form for this) and via django_filters. Django_filters works for the table, but doesn't adjust the sum of weekly planned and remainder for the right week. Also I don't know yet how to let the user select a week in the filter. Basicly i want the user to do next_week = current_week + 1 or prev_week = current_week - 1 with a click on the button. After the click current_week = next/prev_week. I'm new to django and coding in general and I have no clue how … -
Using a VueJS library in Django
I added VueJS to my Django templates project using the VueJS CDN: <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> Now i would like to use this Vue library in my frontend. The problem is that the library does not offer a CDN, so i think i cannot include it on my Django templates just as i did with Vue; is there any way to do this? Or is it impossible because i'm not using Vue with a webpack loader? -
How to synchronously start a game in a chat application in django? [closed]
I'm making a Django based game using chat application. The game is Mafia, one of the party games. I already made the chat application and I can't find a way to synchronously start the game. every client will enter the chat page and I want to start the game when all the players(max 6) enters the room. the game code is already made with javascript - the host chat bot will print out the steps of the game - it changes day and night every minute - when the night comes, maphia gets to kill civilians How do you count how many clients entered the URL(chat page)? How do you start the game after all the clients(6) enters the room? -
AttributeError: 'QuerySet' object has no attribute 'is_staff' [duplicate]
server function that has the failing code: def my_orders(request): if request.is_ajax() and request.method == "POST": username = request.POST.get("username") # if user is staff return all orders userObj = MyUser.objects.filter(username=username) if userObj.is_staff == True: ## this line fails context = { "orders" : Order.objects.all(), "user" : userObj } else: orders = Order.objects.filter(username=username) context = { "orders" : orders, "user" : userObj } return render(request,"orders/my_orders.html", context) else: return HttpResponse("Orders can be seen only via signing in to POO") whereas I already defined MyUser as following in models.py: class MyUser(AbstractBaseUser): is_staff = models.BooleanField(default=False) username = models.CharField(max_length=40, unique=True) USERNAME_FIELD = 'username' so I added this custom MyUser because of is_staff, I thought that would solve the error I am getting. but still I am getting the same error, so what is the solution? -
Bitbucket pipeline use SQL server for testing: Can't open lib 'ODBC Driver 17 for SQL Server'
I'am configuring a pipeline in bitbucket to run my Django tests with a SQL server database. this is my pipeline: image: python:3.7.3 pipelines: branches: master: - step: name: Setup sql image: fabiang/sqlcmd script: - sleep 10 - sqlcmd -S localhost -U sa -P $DB_PASSWORD services: - sqlserver - step: name: Run tests caches: - pip script: # Modify the commands below to build your repository. - python3 -m venv my_env - source my_env/bin/activate - apt-get update && apt-get install -y libldap2-dev - apt-get install python-dev libsasl2-dev gcc -y - apt-get install unixodbc unixodbc-dev -y - pip3 install -r req-dev.txt # setup local .env file - touch DashboardNICU/.env - echo "NICUDASHBOARD_SECRET_KEY=$NICUDASHBOARD_SECRET_KEY" >> DashboardNICU/.env - echo "NICUDASHBOARD_DB_HOST=localhost" >> DashboardNICU/.env - echo "NICUDASHBOARD_DB_NAME=Dashboard" >> DashboardNICU/.env - echo "NICUDASHBOARD_DB_PORT=1433" >> DashboardNICU/.env - echo "NICUDASHBOARD_DB_USER=SA" >> DashboardNICU/.env - echo "NICUDASHBOARD_DB_PASSWORD=$DB_PASSWORD" >> DashboardNICU/.env - python3 manage.py test - step: name: Linter script: # Modify the commands below to build your repository. - pip3 install flake8 - flake8 --exclude=__init__.py migrations/ definitions: services: sqlserver: image: microsoft/mssql-server-linux variables: ACCEPT_EULA: Y SA_PASSWORD: $DB_PASSWORD ports: "1433:1433" But somehow I get the error: django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") … -
Django - ckeditor is not working - customization
I am trying to customize my ckeditor in Django setting like this. But I am getting 500 error once I save the setting. Otherwise the ckeditor is working but if I am trying to customize it, it fails. CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', }, } Can someone help me please, how to make my own "config" without rewriting the basic one, please ? -
How to see related objects when a model tried to be deleted in django
in a large database lets say I have Article_A and Article_A has some comments. Comment_1,Comment_2 and Comment_3. When I tried to delete Article_A I want to show a message to the user says that "Article_A has Comment_1, Comment_2 and Comment_3 and you shouldn't delete them". Moreover I want to show all related objects to Article_A(not only Comments). So should I be aware of all related objects to the Article_A query them? -
Bootstrap Treeview with dynamic data
Can anyone help me convert this PHP code to the Django code? I want to use Bootstrap Treeview Plugin with dynamic data coming from Django backend. I fount this code from a website but unfortunately it is for PHP. And I don't even know the "P" of PHP. <?php //fetch.php $connect = mysqli_connect("localhost", "root", "", "testing1"); $query = " SELECT * FROM country_state_city "; $result = mysqli_query($connect, $query); //$output = array(); while($row = mysqli_fetch_array($result)) { $sub_data["id"] = $row["id"]; $sub_data["name"] = $row["name"]; $sub_data["text"] = $row["name"]; $sub_data["parent_id"] = $row["parent_id"]; $data[] = $sub_data; } foreach($data as $key => &$value) { $output[$value["id"]] = &$value; } foreach($data as $key => &$value) { if($value["parent_id"] && isset($output[$value["parent_id"]])) { $output[$value["parent_id"]]["nodes"][] = &$value; } } foreach($data as $key => &$value) { if($value["parent_id"] && isset($output[$value["parent_id"]])) { unset($data[$key]); } } echo json_encode($data); /*echo '<pre>'; print_r($data); echo '</pre>';*/ ?> This is the table structure they used in the tutorial for PHP. -- -- Table structure for table `country_state_city` -- CREATE TABLE IF NOT EXISTS `country_state_city` ( `id` int(11) NOT NULL, `name` varchar(250) NOT NULL, `parent_id` int(11) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1; -- -- Dumping data for table `country_state_city` -- INSERT INTO `country_state_city` (`id`, `name`, `parent_id`) VALUES (1, 'USA', 0), (2, … -
(Django, Python) If there is no query string or url parameters, how does Subway's customization app work?
I have been analyzing the Subway website because I need to clone it. The problem is that I can't figure out how users can customize their sandwiches using buttons and other components that make backends send data(for example, additional ingredients) from databases. I thought they would use query strings and url parameters but when I look at the urls as I click on ingredient buttons, the urls do not have any query strings but the page shows changes. I have no idea how that is possible. I put the links in it for you to take a look. You can click on 'ADD TOPPINGS' button and see how the url stays exactly same without any query strings or url parameters. customization page: https://order.subway.com/en-US/restaurant/19253/customizer/productSummary/3002/product/30102/category/3/# -
How to display different attribute_values set for different product categories in django-oscar
Dealing with django-oscar. In my catalog i have products of different classes (ProductClass), e.g. Clothing, with attributes: Size, Sex Books with attributes: Author, Genre ... ProductCategory is the same as ProductClass: Clothing, Books, ... How to make sure that when I select a category, in the facet filters are displayed only the attribute values of the selected category , i.e. I select the category Clothes, and in the filter I see: Sizes: S M L XL Sex: M F Now I see in the filter ALL the values of ALL attributes. -
How to add this if statement to a template with Django and improve the views.py
My knowledge of html and Django is very limited but I have this Django project with multiple (12) HTML pages that display information in a table similar to the code below. The table is conditionally displayed if there are any fixes left to make. If any of the data in the fixes was already tested it should be highlighted in red to avoid editing. I recently added the <tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}> bit to do the highlighting but it felt really dumb to have to add it manually to all 12 pages. Is there a way that I can add it as part of an external template? {% extends "admin/base_site.html" %} {% load static %} {% block content %} <p><b>Description:</b> {{ docstring }}</p> {% if count|length %} <p><b>Action:</b> Investigate why and fix.</p> <p style="color:red">If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.</p> <table> <tr bgcolor="#ccc"> <th>Profile</th> <th>Name</th> <th>Type</th> <th>Tested</th> <th>e.g. Device</th> </tr> {% for p in count %} <tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}> <td><a href={{ p.profile_url }}>{{ p.url }}</a></td> <td>{{ p.name }}</td> <td>{{ p.type }}</td> <td>{{ p.tested … -
Django Development: Chrome warns "Change Password"
im new at django and for learning i create a fantasy project. By testing my website i was been warned from my Chrome browser that i should change my password. The exact message is Due to a data breach on a website or in an app your password was disclosed. Chrome recommends changing your password to 127.0.0.1:8000. is there anything in my code that makes this data breach? Thanks for helping! forms.py class RegisterForm(forms.Form): username = forms.CharField( label='Benutzername', max_length=150, required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Username', } ) ) email = forms.EmailField( label='E-Mail Adresse', max_length=254, required=True, widget=forms.EmailInput( attrs={ 'placeholder': 'email@exapmle.com', } ) ) password = forms.CharField( label='Passwort', max_length=254, required=True, widget=forms.PasswordInput( attrs={ 'placeholder': 'Password', } ) ) repeatPassword = forms.CharField( label='Passwort wiederholen', max_length=254, required=True, widget=forms.PasswordInput( attrs={ 'placeholder': 'Password', } ) ) name = forms.CharField( label='Nachname', max_length=150, required=False, widget=forms.TextInput( attrs={ 'placeholder': 'Last Name', } ) ) firstName = forms.CharField( label='Vorname', max_length=150, required=False, widget=forms.TextInput( attrs={ 'placeholder': 'First name', } ) ) def clean(self): cleaned_data = super(RegisterForm, self).clean() username = cleaned_data.get('username') email = cleaned_data.get('email') password = cleaned_data.get('password') repeatPassword = cleaned_data.get('repeatPassword') name = cleaned_data.get('name') firstName = cleaned_data.get('firstName') if not username: raise forms.ValidationError('Enter Username') if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is taken by another one") if not email: raise forms.ValidationError('Enter … -
How to add hostname to HTTP response header in uwsgi?
I was able to add hard coded header to every response that uwsgi is returning, using add-header directive. [uwsgi] add-header = Server: uwsgi-2.0.18 Now, I'd like to add another header X-Forwarded-Host: that returns hostname of the machine where uwsgi server is runing. How can I do that? -
How can i sync schemas in postgressql using django
How can I synchronize two different schemas in django? I mean the following, I have a single database in postgres, and I want users in schema 1 to be saved also in schema 2. what would be the best practice? Thank you.. -
Search result straight to data
I have a couple of models in my app which are: class Recipes(models.Model): title = models.CharField(max_length=200) excerpt = models.TextField(null=True) category = models.CharField(max_length=10) cookTime = models.CharField(max_length=20) prepTime = models.CharField(max_length=20) process = models.TextField(null=True) slug = models.SlugField(max_length=100, unique=True) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=timezone.now) thumb = models.ImageField(default='default.png', blank=True) def get_absolute_url(self): return reverse('recipes:single', args=[self.slug]) class Meta: ordering = ['-published'] def __str__(self): return self.title class RecipeSet(models.Model): set_name = models.CharField(max_length=200) recipe = models.ManyToManyField(Core) published = models.DateField(default=timezone.now) def __str__(self): return self.set_name I'm trying to implement a system where RecipeSet can be used to group recipes, so you could go into the RecipeSet and assign it X amount of recipes and give that group a set_name, this would then be entered into a form and if the set_name does exist, take you straight to a view with the recipes. I can't find any examples where django Q redirects straight to a page, only bringing up a result set and then allowing the user to click the correct link, however, because I only want the correct recipe set to come up, I want to skip the result page and simply redirect to the page hosting the data from RecipeSet. Should I be using a different method to accomplish this … -
extracting zip files to a s3 bucket in django project
I am new to Django and aws. I want to extract the zip file uploaded by the user in Django, files are stored perfectly in the s3 bucket when the user uploads it, but the problem is I am not able to extract the files to the s3 folder new_folder_name = random.randint(0, 68764446643313679) folder_unzip = os.path.join(settings.MEDIA_ROOT, 'Unzipped') print(folder_unzip) file_path = os.path.join(folder_unzip, str(new_folder_name)) zip_file = zipfile.ZipFile(self.ebook) zip_file.extractall(file_path) Can anyone help me with this -
django rest frame work API Test case (Authentication needed)
I am using (simple JWT rest framework) as a default AUTHENTICATION CLASSES Now I want to write an API test case for one of my view which needed authentication I don't know how to add "access" token and how to use this in rest framework test cases I will be thankful if you answer to my question