Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My website shows only 'Authentication/index.html' not the content . I am very new to programming language, how to fix this problem
System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 13, 2022 - 22:57:16 Django version 2.1, using settings 'gfg.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
Ajax request with a response from a different Django View
I am trying to get my head around executing the following idea using Django and Ajax. I already understand how to implement the validation email side of things and the JQuery required to change button colors etc. My question solely relates to how I should set up the Ajax interaction between two different views. What I would like to be able to do is; A 'validate email' button is clicked on a webpage and a request is sent via Ajax to a Django view (validate_view()) - the button changes colour to Orange. Then, validate_view() sends an email with an activation link back to the Django server and activate_view() captures the uidb64 and token and updates the database, job done. My question is, how do I then send a response back to the page? (primarily to change the original button colour to Green) -
DRF: How to add annotates when create an object manually?
Currently I'm trying to create an expected json to use in my test: @pytest.mark.django_db(databases=['default']) def test_retrieve_boards(api_client): board = baker.make(Board) objs = BoardSerializerRetrieve(board) print(objs.data) url = f'{boards_endpoint}{board.id}/' response = api_client().get(url) assert response.status_code == 200 But i'm receiving the following error: AttributeError: Got AttributeError when attempting to get a value for field `cards_ids` on serializer `BoardSerializerRetrieve`. E The serializer field might be named incorrectly and not match any attribute or key on the `Board` instance. E Original exception text was: 'Board' object has no attribute 'cards_ids' Currently cards_idsare added on my viewSet on get_queryset method: def get_queryset(self): #TODO: last update by. #TODO: public collections. """Get the proper queryset for an action. Returns: A queryset object according to the request type. """ if "pk" in self.kwargs: board_uuid = self.kwargs["pk"] qs = ( self.queryset .filter(id=board_uuid) .annotate(cards_ids=ArrayAgg("card__card_key")) ) return qs return self.queryset and this is my serializer: class BoardSerializerRetrieve(serializers.ModelSerializer): """Serializer used when retrieve a board When retrieve a board we need to show some informations like last version of this board and the cards ids that are related to this boards, this serializer will show these informations. """ last_version = serializers.SerializerMethodField() cards_ids = serializers.ListField(child=serializers.IntegerField()) def get_last_version(self, instance): last_version = instance.history.first().prev_record return HistoricalRecordSerializer(last_version).data class Meta: model … -
ValueError: Cannot assign must be a model instance
I'm doing a query to get the chocies from a charfield and assign them. But at the moment I want to save the form in my view I am getting this error. What I can do? ValueError: Cannot assign "'17'": "Con_Transaccioncab.doc_id" must be a "Adm_Documento" instance. In the form I retrieve and assign the options to the field form.py class Con_MovimientosForm(ModelForm): class Meta: model = Con_Transaccioncab fields = '__all__' exclude = ['cab_estado'] widgets = { 'emp_id': HiddenInput(), 'per_id': HiddenInput(), 'suc_id': HiddenInput(), 'cab_numero': HiddenInput(), 'cab_estadocon': RadioSelect, 'cab_escambpat': CheckboxInput, 'cab_fecha': DatePickerInput(format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date}), } def __init__(self, *args, **kwargs): self.AIGN_EMP_ID = kwargs.pop("AIGN_EMP_ID") self.AIGN_PER_ID = kwargs.pop("AIGN_PER_ID") # -------------------------------------------------------------------------------------- self.AIGN_OPCIONES = kwargs.pop("AIGN_OPCIONES") self.PERMISOS = [] # para recuperar los permisos de la tabla __json_values = json.loads(json.dumps(self.AIGN_OPCIONES)) self.PERMISOS = recuperarPermisos(__json_values, self._meta.model.get_table_name(self._meta.model)) # -------------------------------------------------------------------------------------- super(Con_MovimientosForm, self).__init__(*args, **kwargs) self.fields['cab_estadocon'].required = False self.fields['cab_numero'].required = False # here I am assigned the choices to the field self.fields['doc_id'] = ChoiceField(label='Acción: ', choices=self.get_choices(), required=False) for form in self.visible_fields(): form.field.widget.attrs['placeholder'] = Form_CSS.fields_placeholder + form.field.label.lower() form.field.widget.attrs['autocomplete'] = Form_CSS.fields_autocomplete form.field.widget.attrs['class'] = Form_CSS.fields_attr_class self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_id = Form_CSS.getFormID(self) self.helper.attrs = Form_CSS.form_attrs self.helper.form_tag = True self.helper.form_error_title = Form_CSS.form_err_title self.helper.form_class = Form_CSS.form_class self.helper.label_class = Form_CSS.fields_label_class self.helper.field_class = 'col-sm-5' self.helper.layout = Layout( Div( DivHeaderWithButtons(instance_pk=self.instance.pk, … -
Spanning relationship to obtain field value with .annotate() and .values() clauses
I'm making some computations using values & annotate on queryset. Let's consider this model: class Foo(models.Model): fk_bar = models.ForeignKey(to=Bar, ....) foo_val = models.IntegerField(...) class Bar(models.Model): attr = models.Charfield(...) val = models.IntegerField(...) So I can do: Foo.object.all().values("fk_bar") in order to group by the foreign relationship (some Foo might point to the same Bar). Then I can do Foo.object.all().values("fk_bar").annotate(qte=Sum("foo_val")) To the the sum of foo_val for all the object with the same fk_bar, which yields something like: {"fk_bar":<int>, "qte": <int>} However I want the resulting dictionnary to calso contain Bar.attr, e.g. something like: Foo.object.all().values("fk_bar").annotate(qte=Sum("foo_val")).annotate(bar_attr="fk_bar__attr") To get something like: {"fk_bar":<int>, "qte": <int>, "bar_attr":<str>} However that fails (TypeError: Queryset.annotate() received a non-expression). Any ways to go around this? -
Python datetime.today() Showing different time in different python programms
I am having 2 different python file, views.py in django and a test.py .I use test.py to write a specific function and check if iam getting desired output,and if yes, i will copy that code to views.py in my django project. Today i was writting a function to calculate time intervals of 15 mins and populate a list. When i was trying to do print('Today: ',datetime.today()) in test.py it was giving the correct output and a different output in views.py Here's the output in both test.py: Today: 2022-01-13 20:28:45.613094 views.py: Today: 2022-01-13 14:58:25.850835 Note:In my views.py there are other function which uses datetime libraries but iam sure that they are not interfering with each other Here's the Code i use to generate a list of time with interval of 15 mins: def datetime_range(start, end, delta): current = start while current <= end: yield current current += delta def create(): print('Today: ',datetime.today()) #This is where the problem occurs! a=datetime.strftime(datetime.now(),'%I:%M') h=a[0:2] dts = [dt.strftime('%I:%M') for dt in datetime_range(datetime(2022, 1, 1,int(h)), datetime(2022, 1, 1,9), timedelta(minutes=15))] new=[] for d in dts: if datetime.strptime(d,'%I:%M') > datetime.strptime(a,'%I:%M'): new.append(d) return new -
adding a foreignkey set to serializer in django rest framework
I am making a movie-related website and well, every movie or tv show has some trailer videos. I have two models which look like the code provided below. I need to make an API which retrieves an instance of a movie with all it's details. I have done everything that's needed for that and the only thing remaining is returning the details of the trailer videos. The trailer model has a foreignkey field which points to the movie its related to. but I dont know how I can add each movie's video details to the retrieve instance api. Any idea on how I could do that? Models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) price = models.PositiveIntegerField() seasons = models.IntegerField(default=1) duration = models.PositiveIntegerField() statusOf = models.IntegerField(default=1, validators=[MaxValueValidator(4), MinValueValidator(1),]) typeOf = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(1),]) numberOfFilminoRatings = models.PositiveIntegerField(default=0) filminoRating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) rating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) details = models.TextField() salePercentage = models.PositiveIntegerField(default=0) saleExpiration = models.DateTimeField(auto_now_add=True) filmGenre = models.ManyToManyField(Genre) filmActor = models.ManyToManyField(Celebrity, related_name='actor') filmDirector = models.ManyToManyField(Celebrity, related_name='director') filmProducer = models.ManyToManyField(Celebrity, related_name='producer') def __str__(self): return f"{self.title} {self.releaseDate.strftime('%Y')}" class Video(models.Model): videoID = models.AutoField(primary_key=True) duration = models.PositiveIntegerField() qualityHeight = models.PositiveIntegerField() qualityWidth = models.PositiveIntegerField() sizeOf = models.PositiveIntegerField() directoryLocation = models.TextField() film = … -
'DataFrame' object has no attribute 'value_counts' in pandas 0.25
I am using pandas==0.25.0 django-pandas==0.6.1 And I am using value_counts() to group for unique valor in two columns: charges_mean_provinces = whatever.objects.filter(whatever = whatever).values('origin_province','destination_province') df_charges_mean = pd.DataFrame(charges_mean_provinces) df_charges_mean = df_charges_mean.value_counts().to_frame('cantidad').reset_index() In local (development) it work correctly. But in production (I use Heroku), it return this error. 'DataFrame' object has no attribute 'value_counts' Is there other way to group unique valor from two columns without use value_counts? Considering that I can not change my Pandas version in Heroku. Anyway, value_counts is in pandas 0.25 documentation, so, I do not understand the error. -
AttributeError: module 'purchase.views' has no attribute 'viewPDF'
I get this error after followed an tutorial, and I'm pretty new to this, but cant figure out what is wrong, since i have checked, double checked, triple checked and so on. it's probably a simple error but for me as a beginner it's not simple ;) Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\jenny\appdata\local\programs\python\python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\jenny\appdata\local\programs\python\python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self.kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\urls\resolvers.py", line 446, in check for pattern in self.url_patterns: File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\urls\resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\functional.py", line 48, in get res … -
i can not get in varartionb in command line
in my e comerce project i want to create variations for the products and here is my entire code model.py from django.db import models from catagory.models import catagory from django.urls import reverse # Create your models here. class Product(models.Model): product_name = models.CharField(max_length=200,unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500,blank=True) price = models.IntegerField() image = models.ImageField(upload_to='photos/Product') stock = models.IntegerField() is_available= models.BooleanField(default=True) catagory = models.ForeignKey(catagory,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detial',args=[self.catagory.slug,self.slug]) class VariationManager(models.Manager): def colors(self): return super(VariationManager,self).filter(varation_category='color',is_active=True) def sizes(self): return super(VariationManager,self).filter(varation_category='size',is_active=True) varation_category_choice =( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) varation_category = models.CharField(max_length=100,choices= varation_category_choice) varation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now = True) objects = VariationManager() def __str__(self): return self.varation_value views .py def add_cart(request,product_id): product = Product.objects.get(id=product_id) #product_varation=[] if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] #print(key,value) try: varation = Variation.objects.get(varation_category__iexact=key,varation_value__iexact=value) print(varation) except: pass ..... and when i tray to add new product it added successfully but it dose not print the variation in the command line i don't know why it is not working please help me? -
apache wsgi_mod fails to run on python 3.10
I am developing a django app using django 4 and python 3.10. I had a server using apache and mod_wsgi, that used to run an old app using python3.8. I've created a virtual env from 3.10. Command line manage.py is working well. I've changed apache's conf: WSGIDaemonProcess my_app310 python-path=/home/ubuntu/my_app310:/home/ubuntu/venv/my_app310/lib/python3.10/site-packages WSGIProcessGroup my_app310 WSGIScriptAlias / /home/ubuntu/my_app310/my_app310/wsgi.py But I keep getting: [mpm_event:notice] AH00489: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:error] mod_wsgi (pid=1724834): Failed to exec Python script file '/home/ubuntu/my_app310/my_app310/wsgi.py'. [wsgi:error] mod_wsgi (pid=1724834): Exception occurred processing WSGI script '/home/ubuntu/my_app310/my_app310/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/home/ubuntu/venv/my_app310/lib/python3.10/site-packages/django/utils/timezone.py", line 10, in <module> [wsgi:error] import zoneinfo [wsgi:error] ModuleNotFoundError: No module named 'zoneinfo' Which suggest that something is running using python3.8 and not python3.10 (mod_wsgi?). What am I missing? -
django heroku, page content corruption after git push heroku master
Today I added images to my database on the heroku admin page. When I refreshed the Website, the page looked fine. But then when I did "git push heroku master" without making any changes in my current project, the content of my website got corrupted.what could be the reason for this? -
How to post record with pytest-django?
I want to write tests for the project using the pytest-django library. I have a "Context" model with "name"(Charfield) and "description" (Charfield) fields. I want to create a test record through the Django admin panel, but for some reason I can't ( class TestViewContext: def test_post_view_get(self, admin_client): name = 'Sometext' description = 'description' data={'name': name, 'description': description} response = admin_client.post( '/admin/book/context/add/', data=data ) post = Context.objects.filter(name=name, description=description).first() assert post is not None, 'Check new post' -
Docker-compose up command throwing Error while fetching server API version
ERROR: After running a command Docker-compose up It throwing such type of error Traceback (most recent call last): File "docker\api\client.py", line 214, in _retrieve_server_version File "docker\api\daemon.py", line 181, in version File "docker\utils\decorators.py", line 46, in inner File "docker\api\client.py", line 237, in _get File "requests\sessions.py", line 543, in get File "requests\sessions.py", line 530, in request File "requests\sessions.py", line 643, in send File "requests\adapters.py", line 439, in send File "urllib3\connectionpool.py", line 670, in urlopen File "urllib3\connectionpool.py", line 392, in _make_request File "http\client.py", line 1255, in request File "http\client.py", line 1301, in _send_request File "http\client.py", line 1250, in endheaders File "http\client.py", line 1010, in _send_output File "http\client.py", line 950, in send File "docker\transport\npipeconn.py", line 32, in connect File "docker\transport\npipesocket.py", line 23, in wrapped File "docker\transport\npipesocket.py", line 72, in connect File "docker\transport\npipesocket.py", line 52, in connect pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 81, in main File "compose\cli\main.py", line 200, in perform_command File "compose\cli\command.py", line 60, in project_from_options File "compose\cli\command.py", line 152, in get_project File "compose\cli\docker_client.py", line 41, in get_client File "compose\cli\docker_client.py", line 170, in docker_client File "docker\api\client.py", … -
Django rest framework datatables search error
I am using django-rest-framework-datatables and a connection with djongo to mongodb. I have a problem though using the search field. Could you help me please ? Thankyou! DatabaseError at /app/data/ Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "app_person"."id" AS Col1, "app_person"."Name" AS Col2, "app_person"."Surname" AS Col3, "app_person"."BirthDate" AS Col4, "app_person"."Sex" AS Col5 FROM "app_person" WHERE ("app_person"."Name" iLIKE %(0)s OR "app_person"."Surname" iLIKE %(1)s)) subquery Params: ('%A%', '%A%') I have the following code: views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer .html $(document).ready(function() { $('#model').DataTable({ 'serverSide': true, 'stateSave': true, //restore table state on page reload, 'searching': true, 'ajax': '/app/data/?format=datatables', 'columns': [ {'data': 'Name', 'name': 'Name'}, {'data': 'Surname', 'name': 'Surname'}, {'data': 'BirthDate', 'searchable': false}, ] }); }); -
Django: retrieve data for a specific interval
I am going to build my dashboard. Design of this Dashboard is completed. Now the problem is that I did not understand how to retrieve my sum of data from database (mysql) with a specific interval. for example I want to retrieve revenue of last 15 days? how ?? models.py class JaGAnalyticsData(models.Model): project_management_id = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) ecommerce_users = models.FloatField(blank=True, null=True) total_revenue = models.FloatField(blank=True, null=True) conversion_rate = models.FloatField(blank=True, null=True) total_transactions = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'ja_g_analytics_data' views.py @login_required(login_url="/login/") def index(request): jga = JaGAnalyticsData.objects.all() #this line of code will fetch the data from db context = {'jga':jga} #html_template = loader.get_template('home/index.html') #return HttpResponse(html_template.render(context, request)) return render(request, 'home/index.html',context) index.html <div class="row"> <div class="col-sm-6"> <h5 style="margin-top:3px " class="card-title text-uppercase text-muted mb-0">Last week</h5> </div> <div class="col-sm-6"> {{% for i in a %}} <span style="float: right;" class="h4 font-weight-bold">{{i.total_revenue}}</span> {{% end for %}} </div> -
pip-list inside and outside environment give the same list
My question is very similar to this one : Powershell - Pip freeze inside virtual environment listing packages from global pip I'm developing a Django app. I suspect that despite having a virtual environment activated, I'm still working with the global system Python environment: pip-list (or python3 -m pip-list) give the same output whether or not the environment is activated. Same thing with pip freeze / python3 pip freeze. How could I be sure of it, and fix this if necessary? -
Django form at valid() stage failing Validation
I have created a html form which is linked to a django form. When the html form data is passed to the django form it fails at the is form.is_valid():. I think its to do with the formatting but i have read the docs and cant find a solution. form.py class AvailabilityForm(forms.Form): name = forms.CharField(max_length=80, required=True) email = forms.EmailField(max_length=254, required=True) start_date = forms.DateField(input_formats=["%Y-%m-%d", ]) start_time = forms.TimeField(input_formats=["%H:%M", ]) end_date = forms.DateField(input_formats=["%Y-%m-%d#", ]) end_time = forms.TimeField(input_formats=["%H:%M", ]) html form <form class="form-book" action="" method="POST" id="datetimepicker1"> {% csrf_token %} <label for="id_name">Name</label> <input type="text" name="name" maxlength="80" required_id="id_name" required> <label for="id_email">Email</label> <input type="email" required_id="id_email" name="email" max_length="254" required> <label for="id_start_date">Start Date</label> <input type="date" name="start_date" required_id="id_start_date" class="datepicker" required> <label for="id_start_time">Start Time</label> <input type="time" name="start_time" required_id="id_start_time" class="timepicker" required> <label for="id_end_date">End Date</label> <input type="date" name="end_date" required_id="id_end_date" class="datepicker" required> <label for="id_end_time">End Time</label> <input type="time" name="end_time" required_id="id_end_time" class="timepicker" required> <button class="btn btn-signup right" type="submit">Book</button> </form> -
Django/Bootstrap: form-check-inline not working
I want to display radio button inline using Boostrap. I've tryed to add bootstrap form-check-inline class by setting attrs attribute of Django widget. But When I debug, form-check-inline is not applyed. If I add form-check-inline class "manually" in div element containing radiobutton (see below) it works. template.html {{ form.eli_oui_ebo|as_crispy_field }} html page when inspected <div class=""> ***<= here should be applyed form-check-inline class**** <div class="form-check"> <label for="id_id_eli_oui_ebo_0_1" class="form-check-label"> <input type="radio" class="form-check-input" name="eli_oui_ebo" id="id_id_eli_oui_ebo_0_1" value="0" class="test"> Non </label> </div> <div class="form-check"> <label for="id_id_eli_oui_ebo_0_2" class="form-check-label"> <input type="radio" class="form-check-input" name="eli_oui_ebo" id="id_id_eli_oui_ebo_0_2" value="1" class="test"> Oui </label> </div> </div> form.py self.fields['eli_oui_ebo'] = forms.TypedChoiceField(label = 'A eu, dans les 72h, un contact avec un malade Ebola confirmé par RT-PCR',widget=forms.RadioSelect(attrs={'class': 'form-check-inline'},),required=False,choices=[i for i in Thesaurus.options_list(1,'fr') if i != (None,'')], empty_value=None, disabled=DISABLED)``` -
AttributeError: 'NoneType' object has no attribute 'group' trying to create a translation app for multiple language and I run into this error
this is my views.py def translate_app(request): if request.method == "POST": lang = request.POST.get("lang", None) txt = request.POST.get("txt", None) translator = Translator() tr = translator.translate(txt, dest="en") #huasa_tr = translator.translate(txt, dest= 'ha') #igbo_tr = translator.translate(txt, dest='ig') #yoruba_tr = translator.translate(txt, dest='yo') return render(request, 'translate.html', {"result": tr.text}) #result = {"result1":huasa_tr.text, "result2":igbo_tr.text, "result3":yoruba_tr.text}) return render(request, 'translate.html') -
TypeError : got multiple values for argument 'reports_pk'
I am currently running into the above error when trying to print some client details to a CSV file. I do understand what the error is stating, however, I don't see where the error occurs in my code. Please see the below code: Views.py function: def printViewCustomers(reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex connect = pyodbc.connect('DRIVER={SQL Server};' 'DATABASE=' + complexName + ';' ) viewCustomersSQL = ' Select Account , Name , Contact_Person , Telephone , Telephone2 , Fax1 , Fax2, EMail from dbo.Client Where DCLink <> 1 ' cursor = connect.cursor(); cursor.execute(viewCustomersSQL); viewCustomersData = cursor.fetchall() cursor.close() viewCustomers = [] for row in viewCustomersData: rdict = {} rdict["Account"] = row[0] rdict["Name"] = row[1] rdict["Contact_Person"] = row[2] rdict["Telephone"] = row[3] rdict["Telephone2"] = row[4] rdict["Fax1"] = row[5] rdict["Fax2"] = row[6] rdict["Email"] = row[7] viewCustomers.append(rdict) # Starting CSV response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=" ' + complexName + ' Customer Details.csv"' writer = csv.writer(response) writer.writerow([ 'Unit', 'Name', 'Contact Person', 'Telephone 1', 'Telephone 2', 'E-mail' ]) for x in viewCustomers: writer.writerow([ x["Account"], x["Name"], x["Contact_Person"], x["Telephone"], x["Telephone2"], x["Email"] ]) HTML refference to the function: {% extends "main/base.html"%} {% block content%} <h1 style=" text-align: center">Reports</h1> <hr> <br> {% for x in model %} <div class="row … -
drf error, 'Expected a dictionary, but got QuerySet.'
I have a problem with drf function view, I am getting an serializer error like this: {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got QuerySet.', code='invalid')]} Here's my function based view: @api_view(["GET","POST"]) def UserSearch(request): selected_users = Profile.objects.all() serializer = UserProfileSerializer(data=selected_users) if serializer.is_valid(): return Response(data=serializer.data) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) My serializer: class UserProfileSerializer(serializers.ModelSerializer): class Meta: fields = ('user','name','surname','gender','country','city','sport') model = Profile And Profile model: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=True) sport = models.CharField(max_length=60, blank=True) #date_of_birth = models.DateField() def __str__(self): return f"{self.name} {self.surname} from {self.city}" -
How do I create a Django formset out of forms, each with a unique parameter?
In views.py: skill_list = [Skill.objects.get(tag_id=q.tag_id) for q in questions] skill_list = remove_duplicates(skill_list) skill_dict = [{'skill':skill} for skill in skill_list] SkillFormSet = formset_factory(SkillAnswerForm,extra=0) formset = SkillFormSet(initial=skill_dict) for form in formset: print(form.as_table()) In forms.py (please excuse the lack of path class indent): class SkillAnswerForm(forms.Form): def __init__(self,skill): super().__init__() questions = Question.objects.filter(tag_id=skill.tag_id) for question in questions: choices = question.ANSWER_CHOICES self.fields[question] = MultipleChoiceField(choices=choices) skill_id = CharField(max_length=1000) When formset is accessed (but no instantiated) the error TypeError: SkillAnswerForm.__init__() got an unexpected keyword argument 'auto_id' is returned. Thank you! -
How to access a http request.get.form variable into a python class?
I am developing flask app, Here is the app.py code: app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html') # uploading a csv file @app.route('/data', methods=['GET', 'POST']) def data(): if request.method == 'POST': file = request.files['upload-file'] global df df = pd.read_csv(file) columns = df.columns return render_template('data.html',columns=columns, data=df.to_html(max_rows=5, classes="table table-hover"), df=df) @app.route('/data/slamd', methods=['GET', 'POST']) def slamd(): print(data().df) # cannot recognize the df? fixedtargets = request.form.get('fixedtargets') features = request.form.get('features') targets = request.form.get('targets') s = sequential_learning(df) # this is a class return render_template('slamd.html', s=s, fixedtargets=fixedtargets, targets=targets, features=features) in my slamd.py, here is the code: from app import * class sequential_learning: def __init__(self,dataframe): self.dataframe=dataframe def apply_feature_selection_to_df(self,dataframe): features = sequential_process.features self.features_df = self.dataframe[features] Here in my slamd.py file, the variable features are not recognized? How to use these variables features, fixedfeatures and targets inside my class. Note: The df is also not working inside the sequential_process() function? and here is a sample of the view data.html: <div class="row"> <div class="col-sm-6"> <select multiple name="features" class="form-control"> <option value=""></option> {% for col in columns %} <option value="{{col}}">{{col}}</option> {% endfor %} </select> </div> -
module 'django.db.models' has no attribute 'model' Unresolved reference 'module'
I am creating A Realtime chat app using python,django,pycharm. there is following error occurs "Unresolved reference 'models'"